Runtime Architecture

Models runs a language-model pipeline inside the Java process. It does not delegate inference to an Ollama server, a llama.cpp executable, Python, ONNX Runtime, or an HTTP sidecar. External engines are permitted only in benchmark modules as pinned correctness and performance oracles; they are never a production inference path.

Terms such as GGUF, quantization, prefill, decode, KV cache, SIMD, and FFM are introduced in Inference Concepts.

Ownership Boundary

Java owns the behavior that defines the model:

  • GGUF, supported Safetensors, and CACT parsing and memory mapping

  • tokenizer metadata and encoding

  • transformer topology and tensor routing

  • RoPE, grouped-query attention, Gated DeltaNet recurrence, and residual flow

  • KV-cache allocation and growth

  • sampling and generation control

  • streaming and framework contracts

  • diagnostics and runtime-profile selection

The downloadable-model backends run the same Java 25 transformer pipeline with FFM memory segments and the incubating Vector API. backend-java executes every numeric kernel in Java. backend-native substitutes only selected, measured bottleneck kernels with a Models-owned Rust implementation loaded through Java’s final FFM API. It does not embed or call llama.cpp or Ollama. The Java graph remains authoritative, so the backend boundary is narrow and testable.

backend-cuda is the device path for that same graph. Models-owned Rust kernels compiled to PTX run the eligible K-quant projections and grouped-query decode attention on a qualified NVIDIA GPU; unsupported formats and shapes remain on the Vector API, and a declined projection is counted rather than silently dropped. No model server or second inference engine is involved, and Models ships only this one GPU implementation.

backend-apple is also in-process: Java reaches Apple’s on-device Foundation Models framework through a bundled, integrity-checked FFM bridge. It does not launch an executable or communicate with a model server.

Memory And Device Execution

GGUF, Safetensors, and CACT weights are mapped read-only into the Java process address space. They are not copied wholesale into the JVM heap; the operating system pages mapped data through its file cache. Runtime state, including the KV cache and reusable activation workspaces, still consumes JVM heap, so context length and concurrent sessions remain part of capacity planning.

The default downloadable-model path executes on the CPU through Java’s Vector API, with optional Models-owned Rust kernels on qualified bottlenecks. The optional NVIDIA GPU backend offloads eligible Q4_K/Q6_K projections and grouped-query decode attention through Models-owned PTX kernels. Other formats and unsupported devices retain CPU execution. Device availability, memory capacity, and the exact artifact’s numerical and performance gates are separate checks. Apple Silicon’s unified memory avoids physically separate CPU and GPU memory, but unified memory alone does not schedule work on the GPU. Models does not yet execute arbitrary MLX models or dispatch its downloaded-model graph to Metal.

Apple Foundation Models is a separate OS-owned path. Apple controls that model’s weights, memory, and acceleration; it is not an MLX backend for a downloaded ModelJar.

Models runtime architecture

Why A Native Path Exists

Rust accelerates selected numerical operations while Java owns the model pipeline. Historical measurements show advantages for particular native implementations and workloads. Those results do not by themselves prove a missing JVM capability: improved Java arithmetic, weight reuse, scheduling, and call boundaries can change the result on the same JDK.

The current evidence inventory distinguishes demonstrated implementation gains from unresolved compiler or API hypotheses. Several native routes still lack complete causal proof. Correctness repairs and passing CI do not fill that gap; the corresponding evidence records remain unproven. Retention requires measured whole-model benefit and a demonstrated limitation after testing credible Java alternatives. The backend module name does not describe a second model runtime.

Each native route must have:

  1. A Java reference implementation.

  2. Deterministic output comparison against that implementation.

  3. A benchmark on the exact model artifact and runtime selector.

  4. Diagnostics identifying that the route was selected.

  5. Java implementations for operations outside the native capability contract.

  6. Whole-model latency, throughput, startup, allocation, resident-memory, and task-quality checks.

  7. A reproducible JVM limitation after testing Java implementation alternatives.

This boundary also applies to future artifact formats. Supporting an ONNX file, for example, means parsing and executing its supported operations in the Models Java graph. It does not mean embedding or invoking ONNX Runtime.

Retirement Policy

A native operation can be retired when a Java implementation passes the same numerical, task-quality, whole-model performance, and resource gates on the supported hosts. That may follow an implementation improvement on the current JDK or a new JVM/compiler capability. A future JDK release is not automatically necessary, and no retirement date is implied.

Retirement is evidence-driven and operation-specific:

  1. Implement and measure credible Java alternatives.

  2. Run deterministic tensor, token, and state comparisons.

  3. Re-run paired same-host whole-model measurements, including startup and memory.

  4. Select the best validated route, varying it only for demonstrated hardware/input requirements.

  5. Remove native code and support routines once no supported route needs them.

An inactive implementation with a recorded speedup receives a correctness and performance investigation before deletion. An active implementation with incomplete proof is not dead code.

GGUF Data Flow

The pure-Java backend memory-maps GGUF weights and exposes aligned MemorySegment slices instead of materializing complete float tensors.

token
  -> embedding
  -> N x (
       RMSNorm
       -> Q/K/V projections
       -> RoPE
       -> grouped-query attention
       -> output projection
       -> residual
       -> RMSNorm
       -> SwiGLU feed-forward network
       -> residual
     )
  -> final RMSNorm
  -> output logits
  -> sampler

The KV cache starts with 16 positions and grows geometrically. Loading a model therefore does not allocate its full advertised context length. The models.purejava.maxContextLength property can impose a lower hard runtime limit without changing the model metadata exposed to callers.

Dense Qwen3.5 uses the same mapped-weight and sampling infrastructure but a hybrid graph: periodic full-attention layers use the KV cache, while the other layers update bounded convolution and Gated DeltaNet recurrence state. That path projects bounded prompt chunks through the existing GGUF batch kernels, then advances convolution and recurrence state in token order. Its state and activation workspaces belong to each Java session and are reused across prefill and decode. The execution planner derives batch and quantized-kernel choices from the tensors actually loaded rather than assuming a Llama-shaped graph. Java Vector API kernels fuse the causal depthwise convolution with SiLU and vectorize the gate transforms and SwiGLU. The corrected integration candidate selects sequential native DeltaNet on compatible FMA hosts and dimensions, and Java otherwise. The approximate chunked implementation is removed. Final whole-model resource and quality gates remain unresolved; this candidate selection is not a published qualification. The model graph and session state remain owned by Java. The implementation does not invoke a FreeToken, Python, or external inference runtime; FreeToken and llama.cpp are test references.

Bidirectional BERT encoders use a separate whole-sequence graph. Models adds token, position, and token-type embeddings, applies learned-bias LayerNorm, executes full non-causal attention and GELU feed-forward blocks, then performs the mean or CLS pooling declared by the artifact. There is no KV cache or vocabulary projection because an encoder neither predicts nor generates a next token. The projection weights remain memory-mapped and use the same Java GGUF batch kernels as decoder models. The graph accepts both WordPiece metadata used by MiniLM and T5/SentencePiece unigram metadata used by Granite embedding models; tokenizer behavior is pinned independently from vector equivalence. For rerankers, Models instead constructs [CLS] query [SEP] document [SEP], applies the matching token-type IDs, retains the CLS hidden state, and executes the artifact’s trained dense-tanh-output classifier head. Corrected classifier tensors are required; embedding pooling is not substituted for the trained scoring head.

DeBERTa-v2 rerankers use their own whole-sequence graph rather than being approximated as BERT. Models preserves the checkpoint’s Unigram normalization, relative-position buckets, content-to-position and position-to-content attention, ContextPooler, and classifier. The pinned mxbai F16 weights expand once to F32 because the measured mapped-F16 projection path was slower; token rows then execute in parallel through the same Java Vector API dot-product kernels.

Safetensors And CACT

For a supported Hugging Face directory, the pure-Java backend validates config.json, tokenizer.json, tokenizer_config.json, and either one model.safetensors file or an indexed shard set. Qwen 2 BF16 matrices remain mapped and execute through the Vectors BF16 batch kernel; the runtime does not convert the checkpoint to GGUF or load Python.

The MobileMoE QAT path validates the official signed group-32 INT4 layout, expert topology, shared expert, QK normalization, and Llama 3 RoPE settings. The source Safetensors file stays mapped. The default runtime prepares its projection matrices as row-major Q8 in the backend-owned Arena, allowing the existing Vector API Q8-by-Q8 kernels and grouped QKV/shared projections to run without a native shim. Closing the backend releases those derived buffers. -Dmodels.mobilemoe.runtimeLayout=packed-int4 retains only the compact mapped weights and executes them directly when memory capacity is the priority.

The CACT path validates the container header, positional tensor inventory, embedded tokenizer, FP16 state, and mixed CQ2/CQ4 matrices before constructing the dedicated Needle 2 graph. CACT support is intentionally tied to that graph rather than presented as a generic tensor-name interchange format.

Relationship To Vectors

Low-level, reusable SIMD and MemorySegment numeric primitives belong in Vectors. Model-specific topology and transformer behavior belong in Models.

Layer Project Responsibility

Model inference

Models

tokenize, plan, execute, cache, sample, and generate

SIMD kernels

vectors-core

reusable dense and quantized numeric primitives

Embedding storage/search

Vectors

indexes, similarity, persistence, and caches

Integration

models-embedding

optional Models-to-Vectors bridge

models-semantic-order uses rank lookup and sparse scalar operations, so it does not depend on Vectors.