Giter Club home page Giter Club logo

java-llama.cpp's Introduction

Java 11+ llama.cpp b3008

Java Bindings for llama.cpp

The main goal of llama.cpp is to run the LLaMA model using 4-bit integer quantization on a MacBook. This repository provides Java bindings for the C++ library.

You are welcome to contribute

  1. Quick Start
    1.1 No Setup required
    1.2 Setup required
  2. Documentation
    2.1 Example
    2.2 Inference
    2.3 Infilling
  3. Android

Note

Now with support for Llama 3, Phi-3, and flash attention

Quick Start

Access this library via Maven:

<dependency>
    <groupId>com.johnsnowlabs.ml</groupId>
    <artifactId>llama</artifactId>
    <version>3.2.1</version>
</dependency>

There are multiple examples:

No Setup required

We support CPU inference for the following platforms out of the box:

  • Linux x86-64, aarch64
  • MacOS x86-64, aarch64 (M1)
  • Windows x86-64, x64, arm (32 bit)

If any of these match your platform, you can include the Maven dependency and get started.

Setup required

If none of the above listed platforms matches yours, currently you have to compile the library yourself (also if you want GPU acceleration, see below).

This requires:

  • Git
  • A C++11 conforming compiler
  • The cmake build system
  • Java, Maven, and setting JAVA_HOME

Make sure everything works by running

g++ -v  # depending on your compiler
java -version
mvn -v
echo $JAVA_HOME # for linux/macos
echo %JAVA_HOME% # for windows

Then, checkout llama.cpp to know which build arguments to use (e.g. for CUDA support). Finally, you have to run following commands in the directory of this repository (java-llama.cpp). Remember to add your build arguments in the fourth line (cmake ..):

mvn compile
mkdir build
cd build
cmake .. # add any other arguments for your backend
cmake --build . --config Release

Tip

Use -DLLAMA_CURL=ON to download models via Java code using ModelParameters#setModelUrl(String).

All required files will be put in a resources directory matching your platform, which will appear in the cmake output. For example something like:

--  Installing files to /java-llama.cpp/src/main/resources/com/johnsnowlabs/nlp/llama/Linux/x86_64

This includes:

  • Linux: libllama.so, libjllama.so
  • MacOS: libllama.dylib, libjllama.dylib, ggml-metal.metal
  • Windows: llama.dll, jllama.dll

If you then compile your own JAR from this directory, you are ready to go. Otherwise, if you still want to use the library as a Maven dependency, see below how to set the necessary paths in order for Java to find your compiled libraries.

Custom llama.cpp Setup (GPU acceleration)

This repository provides default support for CPU based inference. You can compile llama.cpp any way you want, however (see Setup Required). In order to use your self-compiled library, set either of the JVM options:

  • com.johnsnowlabs.nlp.llama.lib.path, for example -Dcom.johnsnowlabs.nlp.llama.lib.path=/directory/containing/lib
  • java.library.path, for example -Djava.library.path=/directory/containing/lib

This repository uses System#mapLibraryName to determine the name of the shared library for you platform. If for any reason your library has a different name, you can set it with

  • com.johnsnowlabs.nlp.llama.lib.name, for example -Dcom.johnsnowlabs.nlp.llama.lib.name=myname.so

For compiling llama.cpp, refer to the official readme for details. The library can be built with the llama.cpp project:

mkdir build
cd build
cmake .. -DBUILD_SHARED_LIBS=ON  # add any other arguments for your backend
cmake --build . --config Release

Look for the shared library in build.

Important

If you are running MacOS with Metal, you have to put the file ggml-metal.metal from build/bin in the same directory as the shared library.

Documentation

Example

This is a short example on how to use this library:

public class Example {

    public static void main(String... args) throws IOException {
        ModelParameters modelParams = new ModelParameters()
                .setModelFilePath("/path/to/model.gguf")
                .setNGpuLayers(43);

        String system = "This is a conversation between User and Llama, a friendly chatbot.\n" +
                "Llama is helpful, kind, honest, good at writing, and never fails to answer any " +
                "requests immediately and with precision.\n";
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
        try (LlamaModel model = new LlamaModel(modelParams)) {
            System.out.print(system);
            String prompt = system;
            while (true) {
                prompt += "\nUser: ";
                System.out.print("\nUser: ");
                String input = reader.readLine();
                prompt += input;
                System.out.print("Llama: ");
                prompt += "\nLlama: ";
                InferenceParameters inferParams = new InferenceParameters(prompt)
                        .setTemperature(0.7f)
                        .setPenalizeNl(true)
                        .setMirostat(InferenceParameters.MiroStat.V2)
                        .setAntiPrompt("\n");
                for (LlamaOutput output : model.generate(inferParams)) {
                    System.out.print(output);
                    prompt += output;
                }
            }
        }
    }
}

Also have a look at the other examples.

Inference

There are multiple inference tasks. In general, LlamaModel is stateless, i.e., you have to append the output of the model to your prompt in order to extend the context. If there is repeated content, however, the library will internally cache this, to improve performance.

ModelParameters modelParams = new ModelParameters().setModelFilePath("/path/to/model.gguf");
InferenceParameters inferParams = new InferenceParameters("Tell me a joke.");
try (LlamaModel model = new LlamaModel(modelParams)) {
    // Stream a response and access more information about each output.
    for (LlamaOutput output : model.generate(inferParams)) {
        System.out.print(output);
    }
    // Calculate a whole response before returning it.
    String response = model.complete(inferParams);
    // Returns the hidden representation of the context + prompt.
    float[] embedding = model.embed("Embed this");
}

Note

Since llama.cpp allocates memory that can't be garbage collected by the JVM, LlamaModel is implemented as an AutoClosable. If you use the objects with try-with blocks like the examples, the memory will be automatically freed when the model is no longer needed. This isn't strictly required, but avoids memory leaks if you use different models throughout the lifecycle of your application.

Infilling

You can simply set InferenceParameters#setInputPrefix(String) and InferenceParameters#setInputSuffix(String).

Model/Inference Configuration

There are two sets of parameters you can configure, ModelParameters and InferenceParameters. Both provide builder classes to ease configuration. ModelParameters are once needed for loading a model, InferenceParameters are needed for every inference task. All non-specified options have sensible defaults.

ModelParameters modelParams = new ModelParameters()
        .setModelFilePath("/path/to/model.gguf")
        .setLoraAdapter("/path/to/lora/adapter")
        .setLoraBase("/path/to/lora/base");
String grammar = """
		root  ::= (expr "=" term "\\n")+
		expr  ::= term ([-+*/] term)*
		term  ::= [0-9]""";
InferenceParameters inferParams = new InferenceParameters("")
        .setGrammar(grammar)
        .setTemperature(0.8);
try (LlamaModel model = new LlamaModel(modelParams)) {
    model.generate(inferParams);
}

Logging

Per default, logs are written to stdout. This can be intercepted via the static method LlamaModel.setLogger(LogFormat, BiConsumer<LogLevel, String>). There is text- and JSON-based logging. The default is JSON. Note, that text-based logging will include additional output of the GGML backend, while JSON-based logging only provides request logs (while still writing GGML messages to stdout). To only change the log format while still writing to stdout, null can be passed for the callback. Logging can be disabled by passing an empty callback.

// Re-direct log messages however you like (e.g. to a logging library)
LlamaModel.setLogger(LogFormat.TEXT, (level, message) -> System.out.println(level.name() + ": " + message));
// Log to stdout, but change the format
LlamaModel.setLogger(LogFormat.TEXT, null);
// Disable logging by passing a no-op
LlamaModel.setLogger(null, (level, message) -> {});

java-llama.cpp's People

Contributors

kherud avatar cestella avatar devintdha avatar autonomicperfectionist avatar samolego avatar hvisser avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.