Concurrent Session Batching
Autoregressive generation normally advances one request by one token, then reads the same model weights again for the next request. Decode is often limited by moving those weights through memory rather than by arithmetic. Advancing several requests together lets Models load quantized weight blocks once and apply them to several independent hidden states.
BatchInferenceBackend exposes that capability without combining request
state. Every InferenceSession owns its sequence position and KV cache. A
batch call shares model weights and projection work, but attention for one
session cannot read or modify another session’s tokens.
The API is intended for runtimes and servers that manage several active
generations. A normal application with one request at a time should continue
to use TextGenerationModel or a framework adapter.
Let the Runtime Form Batches
Most applications should not coordinate token rows themselves. Construct an
InferencePipeline with ContinuousBatchingOptions, then open the ordinary
generation sessions used by conversations:
import com.integrallis.models.backend.purejava.PureJavaBackend;
import com.integrallis.models.runtime.ContinuousBatchingOptions;
import com.integrallis.models.runtime.InferencePipeline;
import java.util.concurrent.Executors;
var batching = ContinuousBatchingOptions.builder()
.maximumBatchSize(4)
.maximumQueuedRequests(64)
.maximumPrefillChunkTokens(128)
.build();
try (var backend = PureJavaBackend.load(gguf);
var pipeline = new InferencePipeline(backend, batching);
var first = pipeline.openGenerationSession();
var second = pipeline.openGenerationSession();
var callers = Executors.newVirtualThreadPerTaskExecutor()) {
var firstAnswer = callers.submit(() -> first.generate(firstPrompt, options));
var secondAnswer = callers.submit(() -> second.generate(secondPrompt, options));
System.out.println(firstAnswer.get());
System.out.println(secondAnswer.get());
var measured = pipeline.continuousBatchingMetrics().orElseThrow();
System.out.println(measured.meanBatchSize());
}
The two generate calls must actually run concurrently to overlap. The scheduler
admits waiting work up to maximumBatchSize, advances one token for every decode-ready
session in a shared backend call, and replaces completed rows with queued work.
By default, prompt ingestion uses each session’s prefill entry point and is split into
maximumPrefillChunkTokens scheduling turns. This bounds how long a newly admitted prompt can
delay existing decodes.
For a model and host where ragged prompt batching has passed a controlled profile, opt in explicitly:
var batching = ContinuousBatchingOptions.builder()
.maximumBatchSize(4)
.maximumPrefillChunkTokens(128)
.batchPrefillAcrossSessions(true)
.build();
The scheduler then groups compatible prompt chunks from active sessions. Every session still owns its position and KV cache. Models rejects this option when the backend has no physical ragged prefill implementation; it does not silently run a sequential compatibility path. The option is disabled by default because correctness and advertised batch capacity do not prove a performance win.
The queue is bounded. maximumQueuedRequests makes overload explicit instead of
allowing request state to grow without limit. batchFormationDelay optionally
holds the first request for a short period when the scheduler was idle; it is not
paid on every token. Treat maximumBatchSize as both a throughput control and a
memory-capacity decision: independent sessions share weights but retain separate
KV state and activations. The batch size is required explicitly: backend capacity
proves correctness and memory bounds, not that a particular model and host become
faster at that size.
VirtualChatModel needs no special batching contract. Give every physical
member a pipeline configured this way, then keep using
pipeline::openGenerationSession as its session factory. Concurrent virtual
conversations routed to the same member can batch. Requests routed to different
members cannot: different weights, templates, and KV representations remain
separate physical schedulers.
The real-weight Qwen3 0.6B integration gate runs two identical conversations concurrently and requires token-exact answers, a largest observed batch of two, and successful per-request metrics. Performance claims still come from the controlled profile below, not from the correctness gate.
The public-runtime profile demonstrates why the scheduler is opt-in. On this 12-logical-core
Intel/Temurin 25 host, four MiniCPM5 requests improved aggregate throughput from 2.092 to
3.406 tokens/s (+62.83%), reduced p50 TTFT from 10.97 to 4.46 seconds, and preserved the exact
output hash; peak RSS rose 8.90%. Qwen3 0.6B did not benefit on the same host: two short requests
regressed 18.02%, while a 149-token prompt with bounded chunks regressed 2.81%. Qualify the exact
model, quantization, concurrency, JDK, and machine before enabling batching in production. The raw
reports and reproduction command are in
benchmark-results/2026-09-07-runtime-continuous-batching/.
The follow-up ragged-prefill profile makes the same boundary concrete. With four unequal prompts,
MiniCPM5 improved from 5.84 to 12.10 prompt tokens/s (+107.2%), while Qwen3 0.6B regressed from
21.36 to 19.60 (-8.2%); both retained the exact same next-step continuation hash. In the complete
MiniCPM runtime profile, enabling ragged prefill improved aggregate generation throughput 5.54%,
p95 TTFT 19.85%, and p50 total request time 9.89%, but worsened p50 TTFT 61.16% because all four
prompts finished together rather than letting the first sequential prompt begin decoding early.
Peak RSS was also 84.52% higher in that run. These throughput, fairness, latency, and memory
tradeoffs are retained in benchmark-results/2026-09-07-ragged-prefill/.
The next implementation flattens compatible positions from those independent prompts into each
physical projection batch. Causal attention remains session-local: all rows write only to their
own KV cache, and a row can read that cache only through its explicit position. On an isolated
eight-vCPU AMD EPYC-Milan host, three counterbalanced fresh-JVM runs improved median ragged-prompt
throughput from 22.51 to 23.82 tokens/s (+5.81%) for MiniCPM5 1B Q4_K_M and from 45.98 to 52.48
tokens/s (+14.12%) for Qwen3 0.6B Q4_0. Every run retained its control output hash, the pinned
MiniCPM real-weight gate matched complete KV buffers and logits exactly, and median peak RSS did
not increase. The raw reports are in
benchmark-results/2026-09-08-flattened-ragged-prefill/.
Advance Active Requests
PureJavaBackend implements BatchInferenceBackend. RustFfmBackend preserves the same contract
while its wrapped Java transformer uses qualified native matrix kernels, so choosing that backend
does not discard session batching. Open one session per request, prefill each prompt, and pass the
active sessions and their current tokens in matching array positions:
import com.integrallis.models.api.BatchInferenceBackend;
import com.integrallis.models.api.InferenceSession;
import com.integrallis.models.backend.purejava.PureJavaBackend;
import java.nio.file.Path;
Path gguf = Path.of("/opt/models/MiniCPM5-1B-Q4_K_M.gguf");
try (PureJavaBackend loaded = PureJavaBackend.load(gguf)) {
BatchInferenceBackend backend = loaded;
if (backend.maxBatchSize() < 2) {
throw new IllegalStateException("This execution plan cannot batch sessions");
}
try (InferenceSession first = backend.openSession();
InferenceSession second = backend.openSession()) {
int[] firstPrompt = backend.tokenizer().encode("Summarize the first document.");
int[] secondPrompt = backend.tokenizer().encode("Summarize the second document.");
int firstToken = argmax(backend.prefill(first, firstPrompt, 0));
int secondToken = argmax(backend.prefill(second, secondPrompt, 0));
var sessions = new InferenceSession[] {first, second};
var tokens = new int[] {firstToken, secondToken};
for (int step = 0; step < 32; step++) {
var logits = backend.forwardBatchTransient(sessions, tokens);
tokens[0] = logits.argmax(0);
tokens[1] = logits.argmax(1);
}
}
}
The example uses greedy selection for brevity. A serving runtime can pass each
row to Sampler with that request’s sampling options and token history.
When backend.supportsRaggedPrefillBatch() is true and the exact deployment has qualified it, the
two independent prefill calls can be replaced with one call:
var promptLogits = backend.prefillBatchTransient(
new InferenceSession[] {first, second},
new int[][] {firstPrompt, secondPrompt});
int firstToken = promptLogits.argmax(0);
int secondToken = promptLogits.argmax(1);
The pure-Java Llama-family implementation can place several new positions from one session in the same physical projection batch. It assigns every row an explicit session and position, stores projected keys and values only in that session’s cache, and applies causal attention through the row position. A later prompt position can therefore see earlier positions from the same session without seeing any other session’s state.
forwardBatchTransient may reuse its logit storage on the next backend call.
Consume each row before invoking the backend again, or call snapshot() when
the complete result must outlive the step. forwardBatch returns stable logits
at the cost of a copy.
The helper used above is:
static int argmax(float[] logits) {
int best = 0;
for (int index = 1; index < logits.length; index++) {
if (logits[index] > logits[best]) {
best = index;
}
}
return best;
}
Session Lifecycle
-
Keep all sessions in one batch owned by the same loaded backend.
-
Preserve the same array index between a session and its input token for each step. The active batch size may change between calls.
-
Serialize calls into one backend. The backend shares reusable activation and logit buffers; sessions isolate sequence state, not concurrent method calls.
-
Close a completed session to release request state. Closing the backend also invalidates its sessions.
-
Use
checkpoint()andrewind(session, checkpoint)to discard a rejected suffix. Usereset(session)to reuse an open session from position zero. -
Never exceed
maxBatchSize(). The value is fixed by the execution plan selected when the model is loaded.
What Is Measured
On the controlled eight-vCPU AMD EPYC-Milan qualification host, four MiniCPM5 1B sessions on Temurin 25 improved aggregate decode throughput from 12.019 to 17.103 tok/s (+42.29%). Per-request TPOT fell from 332.794 to 233.879 ms (-29.72%), and process CPU fell 32.04%. All runs generated the same token sequence and completed without measured garbage collection.
The follow-up memory attribution found a 574 MB mean current-RSS increase in batched mode. The increase was anonymous resident memory: file-backed RSS, which includes the mapped GGUF weights, differed by 12 KB; measured active heap was 8 MB lower; and Native Memory Tracking committed totals were effectively unchanged. JFR localized the transient allocation to Vector API conversion work before the large four-query Q4_K method reached optimized compilation. It was not a steady-state per-token allocation.
GraalVM Community Java 25 is faster for this exact model and host profile. Three
fresh batched processes averaged 27.753 tok/s with 144.131 ms per-request TPOT,
62.27% more throughput than batched Temurin, 38.37% lower TPOT, identical token
hashes, and no measured collections. Mean current RSS was 23.24% higher than
Temurin, so treat available memory and maxBatchSize() as deployment capacity
constraints and qualify the intended model, context, concurrency, JDK, and host
together. The qualified Graal launch includes
-Djdk.graal.MaximumInliningSize=10000.
This profile also selects the two-query Q6_K batch kernel. Against three GraalVM one-query controls, it raises aggregate throughput from 24.660 to 27.753 tok/s (+12.54%), lowers TPOT 11.16%, and lowers process CPU 12.03%. Maximum observed RSS rises 3.89%. All six runs are token-exact and report zero collections.
The versioned attribution, JVM comparison, rejected compiler-directive screens,
and aggregate are under
benchmark-results/certified-20260801/decode/minicpm5-1b-session-memory-nmt/.
Serving Work Still Above the Low-Level API
BatchInferenceBackend performs one transformer step for a caller-supplied active set; it does
not itself provide a queue or scheduling policy. The opt-in InferencePipeline scheduler above
adds bounded admission, dynamic row replacement, and chunked prefill while preserving the regular
generation-session API. It intentionally does not add an HTTP server or silently select a batch
size for the deployment.
