Skip to content
integrallisPublic

About

In-JVM small language model inference

Topics

Resources

Contributing

Security policy

Stars

14 stars

Watchers

0 watching

Forks

Latest commit

 

History

1,841 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

models logo

models

      ███╗   ███╗ ██████╗ ██████╗ ███████╗██╗     ███████╗     ██╗
      ████╗ ████║██╔═══██╗██╔══██╗██╔════╝██║     ██╔════╝     ╚██╗
█████╗██╔████╔██║██║   ██║██║  ██║█████╗  ██║     ███████╗█████╗╚██╗
╚════╝██║╚██╔╝██║██║   ██║██║  ██║██╔══╝  ██║     ╚════██║╚════╝██╔╝
      ██║ ╚═╝ ██║╚██████╔╝██████╔╝███████╗███████╗███████║     ██╔╝
      ╚═╝     ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝╚══════╝     ╚═╝

In-process small-language-model inference for Java 25.

License: Apache 2.0 JDK 25+ MFCQI Documentation

Models is an in-process inference library for Java applications. It loads an open-weight language model and generates text without Python, a separate model server, or a network request.

Models reads GGUF files, Hugging Face Safetensors checkpoint bundles, the architecture-specific CACT artifact used by Needle 2, and ONNX graphs. GGUF commonly packages configuration, tokenizer metadata, and quantized weights in one file. A Safetensors model is a checked bundle of configuration, tokenizer, and one or more weight shards. Efficient inference must map the weights, tokenize input, execute the model layers, maintain context state, and sample and stream output tokens. Models implements that pipeline on Java 25 and uses the Vector API for CPU SIMD execution:

  • backend-java executes every inference kernel in Java.
  • backend-cuda optionally runs the K-quant projections and grouped-query decode attention on a qualified NVIDIA GPU, through our own Rust kernels compiled to PTX. It keeps the Models graph in-process and falls back to the Vector API when the device or artifact is not eligible.
  • backend-native runs the same Java 25 and Vector API pipeline, substituting only selected, measured bottleneck kernels with a small Models-owned Rust library through Java's Foreign Function and Memory (FFM) API.
  • models-backend-onnx executes ONNX graphs in pure Java, with no ONNX Runtime.

On supported Apple Silicon Macs, backend-apple also exposes Apple's OS-managed, on-device SystemLanguageModel to Java through FFM and a small Models-owned Swift binary. It uses Apple Intelligence rather than GGUF weights, and its client plugs into the same Models, LangChain4j, and Spring AI text-generation contract. See the Apple Foundation Models guide.

The native backend is not a wrapper around llama.cpp or Ollama. Those runtimes are controlled performance comparators only. The project intends to replace each Rust kernel with pure Java when a released JDK can provide equivalent correctness and performance. See Runtime architecture for the exact boundary and migration policy.

Models runtime architecture

Capabilities

  • GGUF v2/v3 with memory-mapped tensor access, strict single-file and sharded Safetensors bundles, the CACT artifact used by Needle 2, and ONNX graphs through models-backend-onnx
  • the architectures listed under Supported Architectures
  • GGUF tensor types F32, F16, BF16, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q4_K, Q5_K, Q6_K, MXFP4, TQ1_0, TQ2_0, PQ2_0, and PTQ1_0, plus CACT CQ2/CQ4; Q2_K, Q3_K, Q8_1, and Q8_K are refused at load. backend-native substitutes Rust kernels for BF16, Q4_0, Q5_0, Q5_1, Q8_0, Q4_K, Q5_K, Q6_K, PTQ1_0, and TQ1_0 projections, and backend-cuda for Q4_K and Q6_K
  • SentencePiece, byte-level BPE with the model-declared pre-tokenizer, Gemma 4 BPE, WordPiece, T5 unigram, and Hugging Face tokenizer.json tokenizers, plus the DeBERTa-v2, Needle 2, and Soprano tokenizers
  • grouped-query attention, RoPE, SwiGLU, KV caching, and autoregressive decode
  • sessions with independent KV state over shared weights, shared prefixes forked across sessions, and portable prefixes moved between independently loaded backends; LLaVA prefixes carry their images and are refused unless the receiver expects the same content
  • Qwen3.5 hybrid full-attention/Gated DeltaNet execution with batched prefill and reusable recurrent state
  • greedy, temperature, top-k, top-p, and repetition-penalty sampling
  • tool calling across Qwen, Hermes, Llama 3, GPT-OSS Harmony, Needle 2, Gemma 4, and MiniCPM5 formats, with LangChain4j and Spring AI schema-constrained tool decoding for enumerable arguments; Needle 2 additionally constrains its array protocol from JSON Schema and retrieves the five most relevant tools with its in-model contrastive head. Spring AI ChatClient requests execute registered Java callbacks on both blocking and streaming paths. Generative models receive the result for their follow-up answer; Needle 2 uses deterministic, schema-constrained action selection and a typed result renderer supplied by the application. Empty Needle selections produce a clean no-applicable-tool response instead of leaking model protocol. ModelJars callers can enforce artifact qualification by passing the descriptor capabilities to the adapter
  • in-JVM text embeddings from causal decoders and bidirectional encoders, with model-declared or explicit pooling and vectors tested against llama.cpp; the BERT, EmbeddingGemma, and EmbeddingGemma 2 routes pack independent documents into one pass
  • image input for LLaVA 1.5 with a fixed-resolution CLIP MLP projector
  • typed, calibrated decisions read from one shared prompt prefix (models-decisions), including a Spring AI DecisionModel with opt-in fitted artifacts per question
  • in-process text-to-speech with normalized PCM output, WAV encoding, and incremental audio streaming, from a Soprano GGUF or a Paradee ONNX artifact
  • pure-Java BERT and DeBERTa-v2 cross-encoder reranking from GGUF and Safetensors, with a framework-neutral API plus LangChain4j ScoringModel and Spring AI DocumentPostProcessor adapters
  • plain Java, LangChain4j, Spring AI, Spring Boot, and Tinystruct integrations
  • Apple Foundation Models on supported Apple Silicon Macs
  • framework-neutral guarded RAG
  • adaptive, explainable routing across local and hosted application clients, with bounded conversation affinity, live load and reliability feedback, model-specific cache awareness, and ordered failover
  • compact WordTour semantic-order models

Supported Architectures

Models executes architectures rather than a fixed list of models: a checkpoint loads when its architecture is one of those below. Whether a particular artifact, at a particular quantization, is good enough for a workload is a separate question, answered per artifact by qualification. ModelJars publishes the qualified artifacts, and the qualification ledger holds the exact SHA, workload, backend, and measurements behind each.

Each architecture below has a test in this repository that runs published weights.

Architecture Metadata key Role Format
Llama llama text generation GGUF
Gemma 3 gemma3 text generation GGUF
Qwen2, Qwen2.5 qwen2; Qwen2ForCausalLM text generation GGUF; Safetensors (BF16)
Qwen3 qwen3 text generation GGUF
Qwen3.5 (hybrid Gated DeltaNet) qwen35 text generation GGUF
Bonsai 2 (Qwen3.5 with Prism Hadamard transforms) qwen35 with prism.hadamard.version text generation GGUF (PTQ1_0)
EdgeRock edgerock text generation GGUF
SmolLM3 smollm3 text generation GGUF
Granite granite text generation GGUF
Maple (sliding-window attention) maple text generation GGUF
Gemma 4, including routed experts gemma4 text generation GGUF
Flint (mixture of experts) flint text generation GGUF
GPT-OSS gpt-oss text generation, Harmony tools Safetensors (MXFP4)
MobileMoE mobilemoe text generation Safetensors (QAT INT4)
Needle 2 CACT tool selection CACT
LLaVA 1.5 Llama text model + clip projector image and text input GGUF
BERT, MiniLM, Nomic BERT bert, nomic-bert embeddings, cross-encoder reranking GGUF
EmbeddingGemma 2 gemma-embedding2 embeddings GGUF
DeBERTa-v2 DebertaV2ForSequenceClassification cross-encoder reranking Safetensors
ModernBERT modern-bert typed decisions GGUF
Soprano soprano_tts text-to-speech GGUF
Paradee ONNX graph text-to-speech ONNX
Apple Foundation Models OS-managed text generation none (on-device system model)

backend-native runs the same graphs with Rust kernels substituted for the projections listed above. ModernBERT decisions run on backend-java only.

These are checked against llama.cpp on one published artifact each, under the frozen protocol in experiments/architecture-parity/: identical prompt tokenization, and teacher-forced next-token top-1 agreement of at least 0.95 with mean KL at most 0.02 and p99 KL at most 0.25: gemma, gemma2, hunyuan-dense, phi3, mistral3, mellum, qwen3moe, qwen35moe, qwen3next, lfm2, lfm2moe, deepseek2, gemma3n, and GPT-OSS from GGUF. EmbeddingGemma matches llama-embedding at cosine 0.999 or better, and GLiNER2 entity extraction matches the publisher's gliner2 package (identical spans, scores within 1e-3). The artifacts and results are committed, and a replay test runs them on the published weights. Agreement with llama.cpp is not a qualification.

Qwen3.5 vision and multi-token prediction, and LLaVA projectors other than the fixed-resolution CLIP MLP (Qwen-VL, SigLIP, any-resolution), are not supported.

Install

Models requires Java 25 or newer. For a versioned, qualified artifact, add ModelJars and the marker JAR for the selected model:

val modeljarsVersion = providers.gradleProperty("modeljarsVersion").get()

dependencies {
    implementation("org.modeljars:modeljars:$modeljarsVersion")
    implementation(
        "org.modeljars.huggingface:" +
            "ggml-org.qwen3-0.6b-gguf.q4_0:" +
            "3.0.0-q4_0.1",
    )
}

The ModelJars facade brings Models and both execution backends, then selects the backend qualified for that exact artifact. Applications that manage their own GGUF files can depend on Models directly:

val modelsVersion = providers.gradleProperty("modelsVersion").get()

dependencies {
    implementation("com.integrallis:models:$modelsVersion")
    implementation("com.integrallis:backend-java:$modelsVersion") // or backend-native
}

For qualified NVIDIA acceleration, add backend-cuda. One sm_80 PTX module ships inside the jar for every device of compute capability 8.0 or above, so no external runtime is installed; the path is opt-in through CudaGgufBatchedMatrixKernel.open() and falls back to the Vector API when the device or artifact is not eligible. See Java GPU acceleration.

Use Apple's on-device system model on a supported Apple Silicon Mac:

dependencies {
    implementation("com.integrallis:backend-apple:$modelsVersion")
}

Model marker artifacts, checksums, variants, and measured runtime profiles are provided by ModelJars.org. ModelJars is a separate project and depends on Models; the Models artifacts remain usable without a catalog dependency.

Quick Start

import static org.modeljars.catalog.Qwen3_0_6b_Q4_0.MODEL;

var options = SamplingOptions.builder()
    .temperature(0.0f)
    .maxTokens(128)
    .build();

try (var runtime = ModelJars.openRuntime(MODEL)) {
    ModelPrompt prompt = runtime.chatTemplate().render(List.of(
        ChatMessage.system("Classify the user's intent in one phrase."),
        ChatMessage.user("I want to cancel my order")));
    String result = runtime.model().generate(prompt, options);
    System.out.println(result);
}

ModelJars.openRuntime resolves the pinned artifact, downloads and verifies it when needed, chooses its qualified Models backend and chat template, and applies a matching performance profile. Applications that manage their own GGUF files, supported Hugging Face directories, or CACT artifacts can use the lower-level loaders described in the Using Models guide. The two loaders take these prefill routes:

  • PureJavaBackend.load(Path) installs the bundled Rust projection kernel when backend-native and the matching models-kernels-<platform> jar are on the runtime classpath, and otherwise runs every kernel in Java with the Vector API. -Dmodels.purejava.nativeKernels=false keeps it on the Vector API, and so does passing GgufBatchedMatrixKernel.none() to a kernel-taking load overload.
  • RustFfmBackend.load(Path), from backend-native with the matching models-kernels-<platform> jar on the runtime classpath, installs the bundled Rust projection kernel and fails when the library is missing. ModelJars loads artifacts qualified on backend-native through this loader.

diagnostics() on the backend or the pipeline reports which route was taken, in its native-batched-matrix-kernel and native-batched-attention-kernel decisions. Record that route beside any published measurement.

Wrap either backend in InferencePipeline for ownership-safe access to the tokenizer, model metadata, active context window, structured prefill, forward-pass logits, reset, checkpoint, rewind, and measurements for the most recent generation. pipeline.lastGenerationMetrics() reports tokenization, prompt preparation, prefill, time to first token, decode and total duration, along with token counts, prompt-cache reuse, and decode throughput.

Batch-capable backends can also open one TextGenerationSession per conversation. Sessions share the loaded model weights but keep independent KV state, exact prompt-prefix reuse, and metrics:

try (var pipeline = new InferencePipeline(PureJavaBackend.load(gguf));
     var conversation = pipeline.openGenerationSession()) {
    String answer = conversation.generate(prompt, options);
    var cache = conversation.lastGenerationMetrics().promptCache();
}

Servers can construct the pipeline with ContinuousBatchingOptions to batch concurrent decode steps. Qualified deployments can additionally opt into batchPrefillAcrossSessions(true) for unequal prompt chunks. Both choices remain explicit because the exact model, quantization, batch size, JVM, and host determine whether shared passes improve latency, throughput, and memory. See the session batching guide.

For speech synthesis, add com.integrallis:models-audio and open a qualified Soprano artifact directly or through ModelJars:

try (var speech = SopranoTextToSpeechModel.loadNative(modelPath)) {
    var audio = speech.synthesize("The JVM can speak for itself.");
    Files.write(Path.of("speech.wav"), WavEncoder.pcm16(audio));
}

See the Text-to-speech guide for streaming, supported controls, and the qualification contract.

Needle 2 CACT artifacts use the same public prompt and parsing APIs. The ChatTemplate.NEEDLE2 renderer emits the model's raw tool-schema envelope and ToolCallScanner recovers its array-wrapped calls; callers do not need to reproduce the CACT reference prompt by hand.

import static org.modeljars.catalog.Cactus_Compute_Needle2_Cact_Cq2_Mixed.MODEL;

var weatherTool = new ToolSpec(
    "get_weather", "Get weather for a city.",
    "{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},"
        + "\"required\":[\"city\"]}");
var options = SamplingOptions.builder().temperature(0).maxTokens(128).build();

try (var runtime = ModelJars.openRuntime(MODEL)) {
    var tools = List.of(weatherTool);
    var prompt = runtime.chatTemplate().render(
        List.of(ChatMessage.user("weather in Lagos")), tools);
    var constraint = ToolCallTokenConstraints.compile(
        runtime.tokenizer(), runtime.chatTemplate().toolSyntax(), tools,
        ignored -> List.of()).orElseThrow();
    var output = runtime.pipeline().generate(prompt, options, constraint);
    var calls = ToolCallScanner.scan(
        output, runtime.chatTemplate().toolSyntax()).toolCalls();
}

The loaded InferencePipeline also exposes Needle 2's trained auxiliary heads through AuxiliaryTextGenerationModel. ToolSpecSelector uses the contrastive head to reduce declarations larger than five tools and keeps a bounded cache of schema embeddings. The LangChain4j and Spring AI adapters apply that selection automatically before rendering the prompt and compiling its decoding grammar.

Streaming uses the same loaded model:

try (var runtime = ModelJars.openRuntime(MODEL)) {
    var prompt = runtime.chatTemplate().render(
        List.of(ChatMessage.user("Explain local inference in one sentence.")));
    runtime.model().generate(prompt, options, new TokenStream() {
        @Override
        public void onToken(String token) {
            System.out.print(token);
        }

        @Override
        public void onComplete() {
            System.out.println();
        }

        @Override
        public void onError(Throwable error) {
            error.printStackTrace();
        }
    });
}

Backend diagnostics expose the exact plan selected for the loaded model:

try (var runtime = ModelJars.openRuntime(MODEL)) {
    runtime.model().diagnostics().optimizations().forEach(System.out::println);
}

Profile matching, explicit overrides, and every execution-plan switch are documented in Execution planning.

Integrations

Integration Module Surface
Plain Java models-runtime GenerationLoop and TokenStream
LangChain4j models-langchain4j blocking and streaming chat, embeddings, and cross-encoder scoring
Spring AI models-spring-ai observed blocking and streaming chat, embeddings, document reranking, and qualified ChatClient tool execution
Spring Boot models-spring-boot-starter local Spring AI ChatModel, opt-in DecisionModel, observations, and token-usage meters
Tinystruct models-tinystruct TypeSafe semantic dispatch, chat, embedding, and reranking adapters
Typed decisions models-decisions calibrated multiple-choice decisions read from one shared prompt prefix
Guarded RAG models-rag retrieval abstention, citation validation, and fallback
Model routing models-router adaptive selection and failover across in-process and hosted clients, with hard per-request capability and data-boundary requirements, without a provider SDK dependency
Vector storage models-embedding optional bridge to vectors
Speech models-audio Soprano and Paradee text-to-speech with incremental PCM streaming
Semantic order models-semantic-order compact WordTour semantic-order models
Apple on-device model backend-apple Apple Foundation Models through Java FFM
NVIDIA GPU acceleration backend-cuda optional Rust-authored PTX K-quant projections and decode attention
ONNX graphs models-backend-onnx in-process, pure-Java execution of ONNX models, never ONNX Runtime

These adapters are implemented and tested against the same backend contracts; they do not select hidden inference paths. Their framework dependencies are caller-owned, and CI composes them with the corresponding Vectors adapters and starter across the supported versions. See the guides for LangChain4j, Spring AI, and Spring Boot. See Model routing to combine those local clients with hosted models while preserving framework-native requests.

For a tool turn whose prompt may leave the process, make both decisions explicit:

var requirements = RoutingRequirements.builder()
    .requireCapability("tool-calling")
    .dataBoundary(RoutingDataBoundary.REMOTE_ALLOWED)
    .build();
var selected = fleet.route(request, requirements);

Use RoutingDataBoundary.LOCAL_ONLY for unredacted sensitive input. The router enforces declared capabilities and the boundary before it scores candidates; an application still owns provider credentials and clients through ModelFleet.

Documentation

The documentation site covers architecture, model qualification, execution planning, integrations, guarded RAG, Javadocs, and release testing.

Build

./gradlew build
./gradlew test
./gradlew integrationTest
./gradlew spotlessApply

Real-model tests resolve immutable ModelJars revisions, download missing GGUF files, verify size and SHA-256, and fail if a required model cannot run. The complete test matrix and individual large-model tasks are in Building and testing.

Scope

Models is intended for local and private inference with small, qualified model artifacts. It is not a training framework, a high-throughput GPU serving system, or a claim that every GGUF architecture works. Use the qualification ledger for the exact model, quantization, runtime, workload, and hardware evidence.

License

Licensed under the Apache License 2.0.

About

In-JVM small language model inference

Topics

Resources

Contributing

Security policy

Stars

14 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages