Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
182 changes: 159 additions & 23 deletions src/main/java/org/beehive/jitllm/api/DelegatingSession.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.Set;
import java.util.function.IntConsumer;
import org.beehive.jitllm.inference.CancellableTokenConsumer;
import org.beehive.jitllm.inference.ContinuationFeed;
import org.beehive.jitllm.inference.sampler.Sampler;
import org.beehive.jitllm.model.Model;
import org.beehive.jitllm.model.format.ChatFormat;
Expand Down Expand Up @@ -90,6 +91,12 @@ final class DelegatingSession implements GenerationSession {
*/
private List<Integer> carriedHistory = List.of();

/**
* Whether the last token of {@link #encodedContext} was sampled but never fed: the previous
* turn was cut by its budget or cancelled. A turn that ended on its stop token fed it.
*/
private boolean lastTokenPending;

/**
* How this session executes, resolved once at construction.
*
Expand Down Expand Up @@ -200,20 +207,38 @@ public GenerationResult generate(GenerationRequest request) {
}

boolean promptForm = request.messages() == null;
List<Integer> promptTokens =
promptForm ? encodePrompt(request) : encodeConversation(request);
if (position + promptTokens.size() >= contextLength) {
// Decided before anything changes, so a request refused below leaves the session as it was.
TurnPlan plan = promptForm ? planPrompt(request) : planConversation(request);
int newTokens = plan.full().size() - plan.reused();
if (plan.full().size() >= contextLength) {
return new GenerationResult(
"",
promptTokens.size(),
newTokens,
0,
FinishReason.CONTEXT_FULL,
new GenerationTimings(Duration.ZERO, Duration.ZERO, promptTokens.size(), 0));
new GenerationTimings(Duration.ZERO, Duration.ZERO, newTokens, 0));
}

// Consumed by this turn's prompt, or superseded by a conversation-form request.
carriedHistory = List.of();

if (plan.reset()) {
resetForDivergence();
} else {
// Rewound to the plan's start: everything from there on is fed again.
position = plan.start();
encodedContext.truncate(plan.start());
}
if (plan.seed() != null) {
runtime.reseed(plan.seed());
}
List<Integer> promptTokens =
new ArrayList<>(
plan.full()
.subList(
plan.seed() != null ? plan.start() + 1 : plan.start(),
plan.full().size()));

Sampler sampler =
Sampler.selectSampler(
model.configuration().vocabularySize(),
Expand Down Expand Up @@ -301,13 +326,17 @@ boolean wasCancelled() {
responseTokens.removeLast();
}

int responseStart = position + promptTokens.size();
position += promptTokens.size() + responseTokens.size();
int responseStart = plan.full().size();
position = responseStart + responseTokens.size();
// Exactly what the key/value cache now holds, so the next conversation can be compared
// against it. The terminal stop token is not here for the same reason it is not in
// position: it was removed above.
encodedContext.append(promptTokens);
encodedContext.append(plan.full().subList(plan.start(), plan.full().size()));
encodedContext.append(responseTokens);
// A turn that ended on its stop token fed its last kept token before sampling the stop;
// one cut by the budget or cancelled sampled it and stopped. Only the first is in the
// cache.
lastTokenPending = !hitStopToken && !responseTokens.isEmpty();
started = true;
if (promptForm) {
dropReasoningFromHistory(responseStart, responseTokens);
Expand Down Expand Up @@ -347,10 +376,10 @@ boolean wasCancelled() {

return new GenerationResult(
completion,
promptTokens.size(),
newTokens,
responseTokens.size(),
reason,
timings(promptTokens.size(), responseTokens.size()),
timings(newTokens, responseTokens.size()),
toolCalls);
}

Expand Down Expand Up @@ -440,13 +469,21 @@ private List<Integer> encodePrompt(GenerationRequest request) {
* began; the answer is fed again with the next turn. One that also carries recurrent state
* cannot rewind, because that state has already consumed the reasoning, so it is reset and the
* whole history, answer included, is fed again.
*
* <p>The rewind leaves the generation seed alone, and that is only correct because the next
* turn never trusts it: {@link #planContinuation} always re-feeds the last retained token (here
* the last prompt token, at {@code responseStart - 1}) and, for a loop that feeds the seed,
* reseeds with exactly that token. Before it did, a Llama-style loop fed the seed it was left
* with — the last <i>reasoning</i> token — at {@code responseStart}, one slot ahead of the
* answer.
*/
private void dropReasoningFromHistory(int responseStart, List<Integer> responseTokens) {
List<Integer> answer = answerOf(responseTokens);
if (answer == null) {
return;
}
if (model.configuration().recurrentStateBytes() == 0) {
lastTokenPending = false; // the last prompt token was fed: it produced the response
if (canRewind()) {
position = responseStart;
encodedContext.truncate(responseStart);
carriedHistory = answer;
Expand Down Expand Up @@ -499,31 +536,129 @@ private static List<Integer> assistantTurnTerminator(ChatFormat chatFormat) {
return message.subList(header.size(), message.size());
}

/**
* What one turn feeds, decided before anything about the session changes.
*
* @param full the complete model input this turn continues from: everything the cache should
* hold before the response
* @param start the position the turn starts at, and how much of {@link #encodedContext} it
* keeps; every token of {@code full} from here on is fed
* @param reused how many tokens of {@code full} were already in the cache — what the result
* does not count as prompt tokens
* @param reset whether the sequence is reset first ({@code start} is then 0)
* @param seed for a loop that feeds the seed first: the token to reseed with, {@code
* full[start]}, which the loop then writes at {@code start}; {@code null} to leave the seed
* as the previous turn left it
*/
private record TurnPlan(
List<Integer> full, int start, int reused, boolean reset, Integer seed) {}

/**
* The model's own chat template, continuing whatever the cache holds: the prompt form always
* extends the session's history, so the whole retained context is the common prefix.
*/
private TurnPlan planPrompt(GenerationRequest request) {
List<Integer> full = new ArrayList<>(encodedContext.tokens());
full.addAll(encodePrompt(request));
return planContinuation(full, encodedContext.size());
}

/**
* Encodes the whole conversation, and feeds the model only the part it does not already hold.
*
* <p>The session is a <b>cache, not a memory</b> [§2]: what it retains is derived from the
* request and never added to it. So the encoded input is computed in full, every time, and the
* only question is how much of it has to be sent again.
*
* <p><b>Reuse requires an exact encoded-token prefix.</b> Any divergence — an edited earlier
* turn, an assistant turn the caller rewrote, a tool specification that changed the system
* content — resets the sequence and re-encodes from the start. Correctness does not depend on
* detecting <i>why</i> it diverged, only on refusing to reuse when it did.
* <p><b>What is reused is the longest common encoded-token prefix</b>, when the family's state
* is purely positional: an edited last user turn, or a reasoning model's previous answer
* replayed without its {@code <think>} block, keeps everything up to where the encodings part.
* A family that also carries recurrent state cannot rewind — that state has consumed every
* token — so it reuses only an exact prefix of everything retained, and any divergence resets
* and re-encodes from the start. Correctness does not depend on detecting <i>why</i> it
* diverged.
*/
private List<Integer> encodeConversation(GenerationRequest request) {
private TurnPlan planConversation(GenerationRequest request) {
List<Integer> full = encoder.encode(request.messages(), request.tools());
return planContinuation(full, encodedContext.commonPrefixLength(full));
}

/**
* Where a turn whose input is {@code full} starts, given that the cache holds its first {@code
* common} tokens.
*
* <h2>The slot mapping</h2>
*
* <p>Slot {@code i} of the key/value cache holds {@code encodedContext[i]}, for every {@code i}
* below {@link #position} — except possibly the last, which is <b>pending</b> when the previous
* turn was cut by the budget or cancelled: the loops sample that token and stop without feeding
* it. A turn therefore never starts at {@code common}; it starts one earlier, at {@code R =
* common - 1}, and writes {@code full[R]} into slot {@code R} again. For a slot that was
* written, that recomputes the same entry from the same token and the same prefix; for a
* pending one, it is the write that was missing.
*
* <p>How {@code full[R]} reaches slot {@code R} depends on the generation loop (see {@link
* org.beehive.jitllm.inference.ContinuationFeed}):
*
* <ul>
* <li><b>Seed first</b> (Llama, Mistral, Devstral, Phi3, Granite; every GPU prefill/decode
* loop): at {@code startPosition > 0} the loop feeds the seed at the start position and
* the prompt after it, so the seed is {@code full[R]} and the prompt {@code full[R+1..]}.
* The loops leave the seed as the last token they sampled — already in the cache after a
* stop, pending after a budget cut — so continuing at {@code position} with it, as this
* session used to, wrote that token a second time at {@code position} (or left {@code
* position - 1} unwritten) and shifted the whole new turn one slot to the right.
* <li><b>Prompt only</b> (the Qwen 3 loops: Qwen2/3, Gemma 4, DeepSeek2, LFM2, gpt-oss): the
* seed is never fed after position 0, so the prompt is {@code full[R..]} and the seed is
* left alone.
* </ul>
*
* <p>The seed-is-BOS distinction ({@code PromptIngestion.firstIndex() == 1}) only matters at
* position 0, where both conventions feed a prompt that opens with its seed once. A rewind to
* {@code R >= 1} never sees it, which is why a common prefix shorter than two tokens resets
* instead.
*/
private TurnPlan planContinuation(List<Integer> full, int common) {
if (encodedContext.isEmpty()) {
// Nothing retained: a fresh session, or one just reset. There is nothing to diverge
// from and nothing to undo, so the sequence is left exactly as the model set it up.
return full;
return new TurnPlan(full, 0, 0, false, null);
}
ContinuationFeed feed = continuationFeed();
if (canRewind()) {
boolean seedFirst = feed == ContinuationFeed.SEED_THEN_PROMPT;
// At least one token of full must be left for the prompt itself.
int start = Math.min(common - 1, full.size() - (seedFirst ? 2 : 1));
if (start < 1) {
return new TurnPlan(full, 0, 0, true, null);
}
return new TurnPlan(full, start, common, false, seedFirst ? full.get(start) : null);
}
// Cannot rewind: reuse only an exact prefix of everything retained.
if (common < encodedContext.size()) {
return new TurnPlan(full, 0, 0, true, null);
}
List<Integer> suffix = encodedContext.reusableSuffixOf(full);
if (suffix != null) {
return suffix;
int start = encodedContext.size();
if (feed == ContinuationFeed.PROMPT_ONLY && lastTokenPending) {
// Never consumed — not by the cache, not by recurrent state — so feeding it now is not
// a rewind. It is the write the previous turn skipped.
start--;
}
resetForDivergence();
return full;
return new TurnPlan(full, start, encodedContext.size(), false, null);
}

/** The loop convention this session's state last ran with, or {@code null} if none yet. */
private ContinuationFeed continuationFeed() {
org.beehive.jitllm.inference.state.State state = runtime.executionState();
return state == null ? null : state.continuationFeed();
}

/**
* Whether the cache can be rewound: the family's state is purely positional, and the loop has
* said where it puts a continuation's tokens.
*/
private boolean canRewind() {
return model.configuration().recurrentStateBytes() == 0 && continuationFeed() != null;
}

/**
Expand All @@ -537,7 +672,7 @@ private void resetForDivergence() {
position = 0;
started = false;
encodedContext.clear();
carriedHistory = List.of();
lastTokenPending = false;
runtime.reset();
}

Expand Down Expand Up @@ -567,6 +702,7 @@ public void reset() {
position = 0;
started = false;
encodedContext.clear();
lastTokenPending = false;
// Only this session's logical state. The lowered runtime deliberately does not reach into
// the shared workspace here — that would be another session's turn.
runtime.reset();
Expand Down
13 changes: 13 additions & 0 deletions src/main/java/org/beehive/jitllm/api/EncodedPrefix.java
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,19 @@ List<Integer> tokens() {
return List.copyOf(tokens);
}

/**
* How many leading tokens {@code full} shares with what is retained: the longest common prefix,
* at most {@link #size()}.
*/
int commonPrefixLength(List<Integer> full) {
int limit = Math.min(tokens.size(), full.size());
int i = 0;
while (i < limit && tokens.get(i).equals(full.get(i))) {
i++;
}
return i;
}

/**
* What of {@code full} still has to be encoded.
*
Expand Down
44 changes: 44 additions & 0 deletions src/main/java/org/beehive/jitllm/inference/ContinuationFeed.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright (c) 2024-2026, APT Group, Department of Computer Science,
* The University of Manchester.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.beehive.jitllm.inference;

/**
* Where a generation loop puts a continued turn's tokens, for a call with {@code startPosition >
* 0}.
*
* <p>At position zero every loop agrees: a seed equal to the prompt's first token is fed once
* ({@link PromptIngestion}). A continuation is where the loops differ, and a caller that rewinds
* the key/value cache has to know which one it is talking to, because the two put the same prompt
* one slot apart:
*
* <pre>
* SEED_THEN_PROMPT slot S = seed, slot S+1.. = prompt[0..]
* PROMPT_ONLY slot S = prompt[0], slot S+1.. = prompt[1..] (seed not fed)
* </pre>
*
* <p>Each loop records its own convention on the state it ran with ({@code
* State.recordContinuationFeed}), so the answer comes from the code that has the behaviour rather
* than from a table of families and policies kept beside it. A state no loop has run on yet has
* none, and a caller must then not rewind.
*/
public enum ContinuationFeed {
/** The seed is fed at the start position, and the prompt from the position after it. */
SEED_THEN_PROMPT,
/** The prompt is fed from the start position; the seed is not fed at all. */
PROMPT_ONLY
}
Loading
Loading