Inference Pipeline
InferencePipeline is the advanced Models API for applications that need more
than complete-text generation. It owns one loaded backend and provides access
to the tokenizer, model metadata, active context window, structured prompt
encoding, prefill, forward-pass logits, reset, checkpoint, and rewind.
The same object also implements TextGenerationModel,
ConstrainedTextGenerationModel, and AuxiliaryTextGenerationModel, so an
application can use low-level operations, schema-constrained generation, and
trained model-specific heads without maintaining independent views of backend
state.
Load a Pipeline
Applications that manage their own GGUF file can load either Models backend:
import com.integrallis.models.api.InferenceContextWindow;
import com.integrallis.models.api.ModelMetadata;
import com.integrallis.models.api.ModelPrompt;
import com.integrallis.models.api.Tokenizer;
import com.integrallis.models.backend.purejava.PureJavaBackend;
import com.integrallis.models.runtime.InferencePipeline;
import com.integrallis.models.runtime.chat.ChatMessage;
import com.integrallis.models.runtime.chat.ChatTemplate;
import java.nio.file.Path;
import java.util.List;
Path gguf = Path.of("/opt/models/private-model.gguf");
try (InferencePipeline pipeline =
new InferencePipeline(PureJavaBackend.load(gguf))) {
ModelMetadata metadata = pipeline.metadata();
Tokenizer tokenizer = pipeline.tokenizer();
InferenceContextWindow context = pipeline.contextWindow();
ModelPrompt prompt = ChatTemplate.CHATML.render(
List.of(ChatMessage.user("Name one JVM language.")));
int[] tokens = pipeline.tokenize(prompt);
System.out.printf(
"%s: model context %,d; active capacity %,d%n",
metadata.modelName(), metadata.contextLength(), context.capacity());
}
InferencePipeline owns the backend passed to its constructor. Closing the
pipeline closes the mapped GGUF file, native resources, and inference context.
Do not close or operate the backend separately after transferring it to the
pipeline.
ModelMetadata.contextLength() is the maximum declared by the model.
InferenceContextWindow.capacity() is the number of positions allocated by
the loaded backend. The latter can be smaller when
models.purejava.maxContextLength caps runtime memory use.
Drive Inference Directly
Structured prompts retain the boundary between template-owned control tokens
and ordinary message text. Tokenize the ModelPrompt rather than flattening it
to a String:
pipeline.resetContext();
ModelPrompt prompt = ChatTemplate.CHATML.render(
List.of(ChatMessage.user("Name one JVM language.")));
int[] promptTokens = pipeline.tokenize(prompt);
float[] logits = pipeline.prefill(promptTokens, 0);
int nextToken = argmax(logits);
String tokenText = pipeline.tokenizer().decode(nextToken);
logits = pipeline.forward(nextToken, promptTokens.length);
InferenceContextWindow afterStep = pipeline.contextWindow();
System.out.println("next position: " + afterStep.position().orElseThrow());
prefill and forward return stable logits owned by the caller. The token ID
passed to forward must be in the model vocabulary, and its position must be
the next contiguous context position.
The pipeline serializes state-changing operations. Calling prefill,
forward, resetContext, or rewind invalidates the high-level generation
prefix cache, preventing a later generate call from reusing stale context.
Checkpoint and Rewind
The Java and Rust/FFM GGUF backends retain an exact token prefix and support rollback:
if (pipeline.rewindable()) {
int acceptedPrefix = pipeline.checkpoint();
int candidate = chooseCandidate(logits);
pipeline.forward(candidate, acceptedPrefix);
// Reject the candidate and restore the accepted prefix.
pipeline.rewind(acceptedPrefix);
}
contextWindow().position() reports the next token position when the active
backend is rewindable. It is empty for a backend that cannot expose its current
position. remaining() follows the same rule.
Use High-Level Generation
The owning pipeline remains a normal text-generation model:
ModelPrompt prompt = ChatTemplate.CHATML.render(
List.of(ChatMessage.user("Name one JVM language.")));
String answer = pipeline.generate(prompt, options);
GenerationMetrics metrics = pipeline.lastGenerationMetrics();
System.out.printf(
"TTFT %d ms; decode %.1f tokens/s%n",
metrics.timeToFirstToken().orElseThrow().toMillis(),
metrics.decodeTokensPerSecond());
The snapshot belongs to the runtime, so it measures the work inside the
generation call rather than time spent loading the model or rendering the
prompt. It separates tokenization, prompt preparation, prefill, and decode;
also includes total duration, exact prompt and completion token counts, and
the prompt-prefix cache result. timeToFirstToken() is empty when generation
produces no token. Check available() before reading a newly opened pipeline
and successful() when diagnosing a failed request.
Keep Conversation State Separate
A pipeline’s ordinary generate methods maintain one exact prompt-prefix
lineage. A server or memory application with several conversations must not
send all of them through that single lineage. When the backend supports
independent sessions, open one TextGenerationSession per conversation:
try (InferencePipeline pipeline =
new InferencePipeline(PureJavaBackend.load(gguf));
TextGenerationSession alice = pipeline.openGenerationSession();
TextGenerationSession bob = pipeline.openGenerationSession()) {
String aliceReply = alice.generate(alicePrompt, options);
String bobReply = bob.generate(bobPrompt, options);
PromptCacheMetrics aliceCache =
alice.lastGenerationMetrics().promptCache();
System.out.printf("Alice reused %d prompt tokens%n",
aliceCache.cacheReadInputTokens());
}
Each session owns its context/KV state, retained prompt tokens, and latest metrics. The sessions share the already-loaded model weights; they do not share KV entries with each other. Supply the complete rendered conversation on each call. An exact unchanged prefix is then retained within that conversation and only its suffix is evaluated.
resetContext() clears one session without disturbing the others. Closing a
session releases only its request state. Closing the pipeline closes every
remaining session and then the loaded model. Calls are serialized across the
pipeline because the backend may share transient logits and execution scratch;
this API provides state isolation, not parallel generation. Use
supportsGenerationSessions() when an application may load a backend without
this capability. The pure-Java GGUF backend currently supports it.
These boundaries matter when routing. Different models, or different adapter states of one base model, must keep separate KV lineages unless equality of the actual K/V activations has been established. Conversation affinity can avoid unnecessary switches, while each model-specific session reports the prefix tokens it reused and wrote.
Discover Portable Prefix Support
The portable-prefix API exchanges immutable computed prompt state between backends with the same exact execution identity. Before arranging a transfer, inspect the loaded configuration:
var capabilities = pipeline.portablePromptPrefixCapabilities();
if (!capabilities.supported()) {
System.out.println("Prefix transfer unavailable: " + capabilities.status());
} else {
System.out.println("Shorter boundaries: " + capabilities.truncation());
}
This metadata query does not hash the model, open a generation session, or take the
donor’s generation lock. supportsPortablePromptPrefixes() remains available for existing
callers. The backend SPI adds a default portablePrefixCapabilities() method, so existing
providers retain their boolean result. A legacy provider reports UNSPECIFIED truncation;
callers must not infer support for arbitrary shorter prefixes from that result.
The current Llama decoder route reports ANY_PREFIX: any nonempty prefix up to the captured
length can be retained without recomputation. The first blocking condition is reported for
other configurations: unsupported decoder state, unavailable model identity, activated-adapter
state, attention-kernel state that does not support portable serialization, or a matrix kernel
that has not opted in for its current state and arithmetic.
Attention kernels that implement BatchedCausalAttentionKernel and advertise
supportsPortableState() now serialize and restore their retained KV store
through the same wire format. NativeCausalAttention supports this for
models with multi-head attention (heads == kv_heads); grouped-query attention
remains unsupported for the native attention path. Rust/FFM also requires an
identified native library. A backend without the portable SPI reports
BACKEND_UNSUPPORTED. These are capability reports, not peer-compatibility
decisions or model qualification verdicts. The current codec and eligibility
limits are unchanged.
Complete Checkpoint Contract
Architecture extensions must preserve all state needed to continue at the captured token boundary with the same logits and greedy tokens as local prefill. That includes exact token IDs and positions, attention KV, recurrent convolution and Gated DeltaNet state where present, and any additional persistent branch or memory-bank state. An end-of-prefix recurrent state cannot stand in for an earlier boundary just because the attention KV can be shortened.
RETAINED_CHECKPOINTS describes a future provider that can shorten only to boundaries where
it retained complete state. It does not promise a checkpoint at every token or introduce a
checkpoint enumeration API. Such a provider must reject unavailable boundaries; the caller
can choose a retained boundary or recompute. Current built-in portable prefixes use
ANY_PREFIX; this release work does not yet enable Qwen3.5 hybrid checkpoints.
Compatibility must bind exact weights, tokenizer, cache layout/ABI and effective arithmetic, including kernel binaries and relevant settings. Multimodal extensions must additionally bind image content, projector and preprocessing identity; activated branches and memory anchors must bind their configuration and complete persistent state. A matching architecture name or token count is insufficient.
Frozen prefixes must remain immutable and detached from mutable donor sessions. Import must validate compatibility and bounded lengths before allocating tensors and must produce new owned state without changing an existing receiver session. Forks may share immutable storage; mutable suffixes must stay isolated. Failure or closure must release owned resources without invalidating other owners' retained state. Portable prompt state does not include sampler state, next-token logits, or an entire conversation. Authentication, tenant isolation, transport, placement and transfer-versus-recompute decisions remain the caller’s responsibility.
Transfer a Complete Prefix
A session prefill produces mutable state; freezePrefix captures an immutable
view that can be exported, imported on another backend, and forked into a new
session:
import com.integrallis.models.api.SharedInferencePrefix;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
// Donor side
var session = pipeline.openGenerationSession();
pipeline.prefill(session, systemTokens, 0);
pipeline.prefill(session, userTokens, systemTokens.length);
SharedInferencePrefix prefix = pipeline.freezePrefix(session);
int checkpoint = prefix.checkpoint(); // total tokens captured
// Export
var output = new ByteArrayOutputStream();
pipeline.writePrefix(prefix, checkpoint, new DataOutputStream(output));
byte[] bytes = output.toByteArray();
// Receiver side (same model on another host)
try (var receiver = new InferencePipeline(PureJavaBackend.load(gguf))) {
SharedInferencePrefix imported = receiver.readPrefix(
new DataInputStream(new ByteArrayInputStream(bytes)),
checkpoint,
bytes.length);
// Continue generation from the imported boundary
try (var fork = receiver.forkGenerationSession(imported)) {
int next = receiver.sample(fork, 0.8f);
}
}
writePrefix emits a versioned wire format that includes the backend identity,
dimensions and the decoder payload. If the attention kernel supports portable
state, a 4-byte length field precedes the kernel payload so the receiver can
delegate deserialization back to the same kernel class. The NoKernel path
emits a zero length to keep the format uniform.
readPrefix validates the identity fingerprint and shape before allocating any
tensors, then reconstructs the prefix into receiver-owned state. The imported
prefix is detached from the donor; closing the donor does not invalidate it.
Transfer a Partial Range with Block Assembly
Complete-prefix export requires contiguous tokens starting from zero. For scenarios that need a middle slice or independently verified fragments, the block API exports arbitrary ranges and assembles them atomically on the receiver:
import com.integrallis.models.api.PortablePrefixBlock;
// Donor: export two overlapping ranges independently
var blockOut = new ByteArrayOutputStream();
var dataOut = new DataOutputStream(blockOut);
// First block covers tokens [0, 50)
pipeline.writePrefixBlock(prefix, 0, 50, dataOut);
// Second block covers tokens [30, 100)
pipeline.writePrefixBlock(prefix, 30, 100, dataOut);
byte[] blocks = blockOut.toByteArray();
// Receiver: read the identity header, then assemble
var blockIn = new DataInputStream(new ByteArrayInputStream(blocks));
SharedInferencePrefix assembled = receiver.readPrefixBlocks(
blockIn, 100, blocks.length);
readPrefixBlocks validates every block’s identity and range before
allocating tensors. Overlapping ranges must agree exactly; missing ranges or
duplicate blocks are rejected. The returned prefix behaves like one produced by
readPrefix: immutable, detached, and forkable into a new generation session.
Use Auxiliary Heads
Architectures may carry trained heads in addition to token generation. Needle 2 CACT carries a 128-dimensional contrastive head for tool retrieval and a confidence head. Capabilities are explicit, and unsupported calls fail rather than substituting another model:
if (pipeline.supportsContrastiveEncoding()) {
float[] query = pipeline.encodeContrastive("open the bedroom blinds");
System.out.println(query.length);
}
if (pipeline.supportsConfidenceScoring()) {
ModelPrompt sequence = ModelPrompt.text("complete prompt and generated output");
float confidence = pipeline.scoreConfidence(sequence);
}
ToolSpecSelector builds on the same contrastive head. It caches the declared
schema vectors and selects the five most relevant tools for each query, matching
the qualified Needle 2 prompt policy. All encoding still executes through the
loaded Java backend.
For qualified artifacts, ModelJars selects the proven chat template and backend rather than requiring an application to choose them. See Using Models for that entry point and Concurrent Session Batching for several independent contexts sharing one loaded model.
