Search in sources :

Example 1 with EngineException

use of ai.djl.engine.EngineException in project djl-serving by deepjavalibrary.

the class Connection method connect.

void connect() {
    EventLoopGroup group = PyEnv.getEventLoopGroup();
    try {
        Bootstrap clientBootstrap = new Bootstrap();
        clientBootstrap.group(group).channel(getClientChannel()).remoteAddress(getSocketAddress()).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast("encoder", new RequestEncoder()).addLast("decoder", new OutputDecoder(CodecUtils.MAX_BUFFER_SIZE)).addLast("handler", requestHandler);
            }
        });
        ChannelFuture future = clientBootstrap.connect().sync();
        if (!future.isSuccess()) {
            throw new EngineException("Connection to Python process is failed.");
        }
        channel = future.awaitUninterruptibly().channel();
    } catch (InterruptedException e) {
        logger.error("Exception occurred while creating netty client", e);
        throw new EngineException("Connection to Python process is interrupted.", e);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) KQueueEventLoopGroup(io.netty.channel.kqueue.KQueueEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollDomainSocketChannel(io.netty.channel.epoll.EpollDomainSocketChannel) Channel(io.netty.channel.Channel) KQueueDomainSocketChannel(io.netty.channel.kqueue.KQueueDomainSocketChannel) EngineException(ai.djl.engine.EngineException) Bootstrap(io.netty.bootstrap.Bootstrap)

Example 2 with EngineException

use of ai.djl.engine.EngineException in project djl-serving by deepjavalibrary.

the class PyEnv method init.

static void init() {
    eventLoopGroup = Connection.newEventLoopGroup();
    Path tmp = null;
    try {
        Platform platform = Platform.detectPlatform("python");
        version = platform.getVersion();
        Path cacheDir = Utils.getEngineCacheDir("python");
        logger.debug("Using cache dir: {}", cacheDir);
        Path path = cacheDir.resolve(version);
        engineCacheDir = path.toAbsolutePath().toString();
        if (Files.exists(path)) {
            return;
        }
        Files.createDirectories(cacheDir);
        tmp = Files.createTempDirectory(cacheDir, "tmp");
        Files.createDirectories(tmp.resolve("djl_python"));
        for (String file : platform.getLibraries()) {
            String libPath = '/' + file;
            logger.info("Extracting {} to cache ...", libPath);
            try (InputStream is = PyEnv.class.getResourceAsStream(libPath)) {
                if (is == null) {
                    throw new AssertionError("Python engine script not found: " + libPath);
                }
                Files.copy(is, tmp.resolve(file), StandardCopyOption.REPLACE_EXISTING);
            }
        }
        Utils.moveQuietly(tmp, path);
        tmp = null;
    } catch (IOException e) {
        throw new EngineException("Failed to initialize python engine.", e);
    } finally {
        if (tmp != null) {
            Utils.deleteQuietly(tmp);
        }
    }
}
Also used : Path(java.nio.file.Path) Platform(ai.djl.util.Platform) InputStream(java.io.InputStream) EngineException(ai.djl.engine.EngineException) IOException(java.io.IOException)

Example 3 with EngineException

use of ai.djl.engine.EngineException in project djl by deepjavalibrary.

the class StackBatchifier method batchify.

/**
 * {@inheritDoc}
 */
@Override
public NDList batchify(NDList[] inputs) {
    // each input as NDList might contain several data or labels
    // so those should be batchified with counterpart
    int batchSize = inputs.length;
    int numInputKinds = inputs[0].size();
    // if the NDList is empty
    if (numInputKinds == 0) {
        return new NDList();
    }
    try {
        // stack all the data and labels together
        NDList result = new NDList(numInputKinds);
        for (int i = 0; i < numInputKinds; i++) {
            NDList inputsOfKind = new NDList(batchSize);
            String inputName = inputs[0].get(i).getName();
            for (NDList input : inputs) {
                inputsOfKind.add(input.get(i));
            }
            NDArray stacked = NDArrays.stack(new NDList(inputsOfKind));
            // keep the name for stacked inputs
            stacked.setName(inputName);
            result.add(stacked);
        }
        return result;
    } catch (IndexOutOfBoundsException | EngineException e) {
        // Check if numInputKinds is not consistant for all inputs
        for (NDList input : inputs) {
            if (input.size() != numInputKinds) {
                throw new IllegalArgumentException("You cannot batch data with different numbers of inputs", e);
            }
        }
        // Check if data does not have a consistent shape or type
        for (int i = 0; i < numInputKinds; i++) {
            Shape kindDataShape = inputs[0].get(i).getShape();
            DataType kindDataType = inputs[0].get(i).getDataType();
            for (NDList input : inputs) {
                NDArray currInput = input.get(i);
                if (!currInput.getShape().equals(kindDataShape)) {
                    throw new IllegalArgumentException("You cannot batch data with different input shapes", e);
                }
                if (!currInput.getDataType().equals(kindDataType)) {
                    throw new IllegalArgumentException("You cannot batch data with different input data types", e);
                }
            }
        }
        // Could not clarify cause - rethrow original error.
        throw e;
    }
}
Also used : Shape(ai.djl.ndarray.types.Shape) NDList(ai.djl.ndarray.NDList) EngineException(ai.djl.engine.EngineException) DataType(ai.djl.ndarray.types.DataType) NDArray(ai.djl.ndarray.NDArray)

Example 4 with EngineException

use of ai.djl.engine.EngineException in project djl by deepjavalibrary.

the class TfEngine method newInstance.

static TfEngine newInstance() {
    try {
        LibUtils.loadLibrary();
        eagerSessionHandle = new AtomicReference<>(JavacppUtils.createEagerSession(true, 2, JavacppUtils.getSessionConfig()));
        // call a function from tensorflow-java package to
        // load the native library right here
        // if it throws exception, we can catch it here
        TensorFlow.version();
        return new TfEngine();
    } catch (Throwable t) {
        if (t.getMessage().contains("libstdc++")) {
            // Does not mention .so to work with osx .dylib
            String msg = "There was an issue with your libstdc++ file required for the Tensorflow native library.\n" + "It can be installed or upgraded through gcc by following the instructions on the TensorFlow install page: https://docs.djl.ai/engines/tensorflow/index.html#note";
            throw new EngineException(msg, t);
        }
        throw new EngineException("Failed to load TensorFlow native library", t);
    }
}
Also used : EngineException(ai.djl.engine.EngineException)

Example 5 with EngineException

use of ai.djl.engine.EngineException in project djl by deepjavalibrary.

the class TrtEngine method newInstance.

static Engine newInstance() {
    try {
        LibUtils.loadLibrary();
        JniUtils.initPlugins("");
        String paths = System.getenv("TENSORRT_EXTRA_LIBRARY_PATH");
        if (paths == null) {
            paths = System.getProperty("TENSORRT_EXTRA_LIBRARY_PATH");
        }
        if (paths != null) {
            String[] files = paths.split(",");
            for (String file : files) {
                Path path = Paths.get(file);
                if (Files.notExists(path)) {
                    throw new FileNotFoundException("TensorRT extra Library not found: " + file);
                }
                // NOPMD
                System.load(path.toAbsolutePath().toString());
            }
        }
        return new TrtEngine();
    } catch (Throwable t) {
        throw new EngineException("Failed to load TensorRT native library", t);
    }
}
Also used : Path(java.nio.file.Path) FileNotFoundException(java.io.FileNotFoundException) EngineException(ai.djl.engine.EngineException)

Aggregations

EngineException (ai.djl.engine.EngineException)13 Path (java.nio.file.Path)4 NDArray (ai.djl.ndarray.NDArray)3 OrtException (ai.onnxruntime.OrtException)3 FileNotFoundException (java.io.FileNotFoundException)3 IOException (java.io.IOException)3 NDList (ai.djl.ndarray.NDList)2 DataType (ai.djl.ndarray.types.DataType)2 Shape (ai.djl.ndarray.types.Shape)2 ArrayList (java.util.ArrayList)2 CancellationException (java.util.concurrent.CancellationException)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 Device (ai.djl.Device)1 Input (ai.djl.modality.Input)1 Output (ai.djl.modality.Output)1 Platform (ai.djl.util.Platform)1 OnnxJavaType (ai.onnxruntime.OnnxJavaType)1 OnnxTensor (ai.onnxruntime.OnnxTensor)1 OrtSession (ai.onnxruntime.OrtSession)1 SequenceInfo (ai.onnxruntime.SequenceInfo)1