Embeddings
Models turns text into vectors in the JVM from both dedicated encoder GGUFs and the same decoder GGUFs it generates from.
A causal embedding model runs the decoder stack, stops before the vocabulary projection, and reduces its hidden states. A bidirectional encoder such as BERT or MiniLM runs the complete sequence at once and applies the pooling declared by the GGUF. Both paths can scale the result to unit length.
Producing A Backend
GgufEmbeddingBackend implements EmbeddingBackend over a loaded GGUF model:
dependencies {
implementation("com.integrallis:models-api:0.5.20")
implementation("com.integrallis:backend-java:0.5.20")
}
import com.integrallis.models.api.EmbeddingBackend;
import com.integrallis.models.api.Pooling;
import com.integrallis.models.backend.purejava.GgufEmbeddingBackend;
import com.integrallis.models.backend.purejava.PureJavaBackend;
import java.nio.file.Path;
import java.util.List;
static void embed(Path gguf) {
try (PureJavaBackend backend = PureJavaBackend.load(gguf);
EmbeddingBackend embeddings =
GgufEmbeddingBackend.builder(backend)
.pooling(Pooling.LAST_TOKEN)
.normalize(true)
.build()) {
float[] vector = embeddings.embed("How do I reset my password?");
float[][] batch = embeddings.embedAll(
List.of("Database backups are retained for 30 days.",
"Rotate credentials every 90 days."));
}
}
EmbeddingBackend lives in models-api, so a backend implements it without
inheriting a dependency on Vectors storage.
Internal Batching
embedAll may use a batched prefill internally when the configured backend
supports prefillBatchHiddenStates(), the model uses LAST_TOKEN pooling,
and the document count fits within the backend’s maxBatchSize(). Each
document receives an isolated session so attention is isolated; the batch
amortises per-call setup and uses native matrix kernels when available. When
these conditions are not met --- MEAN or CLS pooling, a single document,
a backend without batch prefill, or a list larger than maxBatchSize() ---
the call falls back to sequential embed(). The caller sees the same vectors
either way; the optimization is transparent.
Resolve the artifact through its marker JAR:
import org.modeljars.ModelJarLocator;
import org.modeljars.ModelJarRegistry;
Path gguf = new ModelJarLocator(ModelJarRegistry.fromClasspath())
.requireLocalPath(MODEL);
Pooling
Pooling reduces one hidden state per token to one vector per text. The correct choice follows from how the model was trained.
Pooling.LAST_TOKEN-
The default. Causal decoder-only embedders such as the Qwen3-Embedding family, where attention is one-directional and only the final position has seen the whole input.
Pooling.MEAN-
Bidirectional encoders, where every position has seen the whole input.
Dedicated encoders own their pooling choice. Do not call pooling(…) for a
BERT/MiniLM or Granite embedding GGUF; Models reads bert.pooling_type and
rejects an override that would silently change the trained representation.
Mean pooling on a last-token model returns vectors that agree with the correct ones at 0.66 cosine. Take the pooling the model card specifies.
normalize(true) is also the default. Unit vectors let a bare dot product stand
in for cosine similarity.
Framework Adapters
For LangChain4j, ModelsEmbeddingModel adapts an EmbeddingBackend to
EmbeddingModel:
import com.integrallis.models.langchain4j.ModelsEmbeddingModel;
try (var model = new ModelsEmbeddingModel(embeddings)) {
Response<List<Embedding>> response =
model.embedAll(List.of(TextSegment.from("a document")));
}
For Spring AI, ModelsSpringAiEmbeddingModel adapts the same backend:
import com.integrallis.models.spring.ai.ModelsSpringAiEmbeddingModel;
import io.micrometer.observation.ObservationRegistry;
try (var model = new ModelsSpringAiEmbeddingModel(
embeddings,
"embeddinggemma-300m-q8_0",
observationRegistry)) {
float[] vector = model.embed("How do I reset my password?");
}
Both adapters own the backend they wrap and close it. They serialize backend
access, so a singleton framework model can safely receive a live query while
another request is ingesting documents even though the local GGUF backend uses
shared encoder scratch state. The Spring AI constructor that accepts an
ObservationRegistry emits the framework’s standard embedding observations
with the supplied model identity. To store the vectors, see Vectors.
Equivalence Gating
We test that Models produces the same vectors as llama.cpp. models-bench
embeds a pinned probe set and compares the result against a pinned llama.cpp
build over the same model bytes:
./gradlew :models-bench:run --args="embedding-equivalence \
--model /path/to/model.gguf \
--report benchmark-results/embedding/model.json"
Exit 0 reproduced, 1 not reproduced, 2 usage or integrity problem. It runs
in seconds: the reference vectors are committed, so the gate needs no local
llama.cpp build.
Probe sets cover single tokens, long input, non-Latin script, code, rare tokens, and ordinary prose. Dedicated encoders additionally pin their tokenizer output and the complete pooled vector. This covers WordPiece for MiniLM and T5/SentencePiece unigram tokenization for Granite, including accented Latin and Japanese input. The gate takes the worst probe.
Two floors, both placed against measurements:
| Run | Min cosine | Max abs(norm - 1) |
|---|---|---|
Correct runtime against the reference |
0.99950 |
2.7e-09 |
MiniLM BERT encoder against the reference |
0.99924 |
4.8e-09 |
Granite multilingual BERT encoder against the reference |
0.999746 |
< 1e-6 |
Mean pooling instead of last-token |
0.66156 |
— |
L2 normalization skipped |
1.00000 |
~11 |
floor |
0.999 |
1e-3 |
Cosine is scale-invariant, so a runtime that skips L2 normalization agrees with a normalized reference at exactly 1.0, and vector length is checked separately.
The gate verifies the probe-set and artifact digests before comparing, and
exits 2 when either has moved.
