Java で高速LLM推論 Jlima の始め方


はじめに

Jlama は、Java で LLM を実行するためのライブラリです。

Jlama は JDK の Vector API により SIMD命令を使うことで高速な推論が可能となっています(Vector API はJDK25時点で Tenth Incubator)。

ここでは、Jlama を(LangChain4j無しで)直接使う例と LangChain4j から使う例を Gradle で試してみます。


プロジェクトの作成

Gradel の init タスクでプロジェクトを生成します。

gradle init  --use-defaults --no-comments --type java-application

生成されたプロジェクトで app/build.gradle.kts に以下の依存を追加します。

import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform

val os   = DefaultNativePlatform.getCurrentOperatingSystem()
val arch = DefaultNativePlatform.getCurrentArchitecture()
val artifact = when {
    os.isMacOsX  && arch.isArm64 -> "osx-aarch_64"
    os.isMacOsX  && arch.isAmd64 -> "osx-x86_64"
    os.isLinux   && arch.isAmd64 -> "linux-x86_64"
    os.isWindows && arch.isAmd64 -> "windows-x86_64"
    else -> throw Error("Unsupported OS: $os, ARCH: $arch")
}

// ...

dependencies {
    implementation("com.github.tjake:jlama-core:0.8.4")
    implementation("com.github.tjake:jlama-native:0.8.4:${artifact}")
}

// ...

Jlama のコアライブラリ jlama-core を依存に追加しています。

jlama-native は環境別の classifier があるので、DefaultNativePlatform から取得して設定しています。


Jlama の利用

App.java を以下のように編集します。

package org.example;

import com.github.tjake.jlama.model.AbstractModel;
import com.github.tjake.jlama.model.ModelSupport;
import com.github.tjake.jlama.model.functions.Generator;
import com.github.tjake.jlama.safetensors.DType;
import com.github.tjake.jlama.safetensors.prompt.PromptContext;
import com.github.tjake.jlama.util.Downloader;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class App {
    public static void main(String[] args) throws IOException {
        File localModelPath = new Downloader(
                "./models",
                "tjake/Llama-3.2-1B-Instruct-JQ4"
        ).huggingFaceModel();

        AbstractModel model = ModelSupport.loadModel(localModelPath, DType.F32, DType.I8);
        PromptContext ctx = model.promptSupport().get()
                .builder()
                .addSystemMessage("You are a helpful chatbot who writes short responses.")
                .addUserMessage("Write a java program to print hello world.")
                .build();

        Generator.Response response = model.generate(UUID.randomUUID(), ctx, 0.0f, 256, (s, f) -> {});
        System.out.println(response.responseText);

    }
}

Downloader で Hugging Face からモデルをダウンロードします。 既にダウンロード済みの場合は、ダウンロード済みのモデルが利用されます。

ダウンロードしたモデルは、ModelSupport.loadModel()AbstractModel としてロードし、model.generate() でプロンプトを渡して結果を得ています。

実行すると以下のように応答を得ることができます。

./gradlew run


Here's a simple Java program to print "Hello World":

 ```java
public class HelloWorld {
    public static void main(String[] args) {
        // Print "Hello World"
        System.out.println("Hello World");
    }
}
 ```

To compile and run this program, you'll need to create a new Java project in your preferred IDE (Integrated Development Environment). Here's a step-by-step guide:   

1. Create a new Java project in your IDE.
2. Create a new Java class file (e.g., `HelloWorld.java`) and paste the above code into it.
3. Compile the code by clicking the "Compile" button or pressing F10.
4. Run the program by clicking the "Run" button or pressing F5.
5. The program will print "Hello World" to the console.

Note: Make sure you have the Java Development Kit (JDK) installed on your system, as it's required to compile and run Java programs.


LangChain4j インテグレーション

LangChain4j のインテグレーションで Jlama を使うことができます。

app/build.gradle.kts に以下の依存を追加します。

dependencies {

    implementation("dev.langchain4j:langchain4j:1.1.0")
    implementation("dev.langchain4j:langchain4j-jlama:1.1.0-beta7")
}

App.java を以下のように編集します。

package org.example;

import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.jlama.JlamaChatModel;

public class App {
    public static void main(String[] args) {
        ChatModel model = JlamaChatModel.builder()
                .modelName("tjake/Llama-3.2-1B-Instruct-JQ4")
                .temperature(0.3f)
                .build();

        ChatResponse chatResponse = model.chat(
                SystemMessage.from("You are helpful chatbot who is a java expert."),
                UserMessage.from("Write a java program to print hello world.")
        );

        System.out.println("\n" + chatResponse.aiMessage().text() + "\n");

    }
}

実行すると、以下のような応答が出力されます。

./gradlew run

Here's a simple Java program that prints "Hello World" to the console:

 ```java
public class HelloWorld {
    public static void main(String[] args) {
        // Print "Hello World"
        System.out.println("Hello World");
    }
}
 ```

To compile and run this program, you'll need to have Java installed on your system. Here are the steps:

1. Create a new Java project in your preferred IDE (Integrated Development Environment) such as Eclipse, IntelliJ IDEA, or NetBeans.
2. Copy the above code into your project's source file (e.g., `HelloWorld.java`).
3. Compile the code by clicking the "Build" button in your IDE or by using the `javac` command in the command line.
4. Run the compiled program by clicking the "Run" button in your IDE or by using the `java` command in the command line.

For example, if you're using Eclipse, you can create a new Java project and add the above code to the `HelloWorld.java` file. Then, you can compile and run the program by clicking the "Run" button in the "Run Configurations" dialog.

LangChain4j インテグレーションを使った場合、モデルはユーザホームの .jlama/models 以下にダウンロードされます。

簡単ですね。