Skip to content

Serve the longest context that fits instead of crashing on a long window - #293

Open
stratika wants to merge 3 commits into
mainfrom
fix/serve-longest-fitting-context
Open

stratika wants to merge 3 commits into
mainfrom
fix/serve-longest-fitting-context

Conversation

@stratika

@stratika stratika commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Without --ctx-size, jitllm serve asked for the model's full window. On long-window models that crashed while sizing the key/value cache. This PR fixes the overflow and makes serve choose the longest context that fits: the model's own window, unless one key/value array can't address it or the GPU memory budget can't hold it. It prints which limit applied. An explicit --ctx-size that can't fit now fails at once with a coded error.

Problem

./jitllm serve -m Llama-3.2-3B-Instruct-F16.gguf --gpu --port 8123

On main this fails during startup:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid number of elements (-536870912): the number of elements cannot be negative
	at ...HalfFloatArray.<init>(HalfFloatArray.java:67)
	at ...TornadoWorkspaces.zeroedHalfFloats(TornadoWorkspaces.java:148)
	at ...State.fillKvFields(State.java:555)

Llama-3.2-3B's window is 131,072 tokens, so one sequence's key/value array has 28 layers × 1024 × 131,072 = 3.76e9 elements. That's more than an int-indexed TornadoVM array can hold, and State.fillKvFields computed the count in an int, which wrapped negative. A user had to know to pass a smaller --ctx-size, and the message didn't say which one.

Changes

  • KeyValueAddressing (new, runtime.memory): one place for the arithmetic. It gives the number of elements in a private or pooled key/value array, and the longest context each can address.

  • State.fillKvFields: counts in long. A context that can't be addressed throws the new GPUL-MEM-004 (KV_CACHE_NOT_ADDRESSABLE), which names the longest context that fits.

  • LocalModels.largestFittingContext(Path, ModelOptions) (@Experimental), via MemoryPreflight, works from metadata only and loads no weights. It returns a ContextFit with:

    • the chosen context;
    • the model's own window;
    • the addressable limit;
    • which limit applied (MODEL, ADDRESSING or MEMORY_BUDGET).

    The budget bound comes from a binary search, over whole key/value blocks, of the existing preflight. A long result is rounded down to a multiple of 1,024 tokens.

  • serve:

    • Without --ctx-size, it uses that context and says why on stderr.
    • With --ctx-size, a context the cache can't address fails with GPUL-MEM-004 before any weight is read.
    • Continuous batching uses the pooled bound, because all its slots share one array.
  • Configuration.keyValueAddressingWidth(): the key/value width the context is sized by. It is kvDim() where all layers share one width. Gemma 4's layers differ, and it refuses kvDim(), so it uses its widest layer. That errs towards a shorter context rather than an array that overflows.

  • KeyValueAddressingTest: element counts, the 3B overflow, private and pooled bounds, and the error message.

Testing

Unit tests: ./mvnw -Pjdk22plus test gives 985 tests, 0 failures (7 skipped).

On an Apple M4 Pro (Metal, TornadoVM 8.2.0 SDK, serve --gpu):

Model, options main This PR
Llama-3.2-3B F16, no --ctx-size Invalid number of elements (-536870912) starts and answers: [server] context 36864 tokens; the model supports 131072, but the GPU memory budget (14GB, --gpu-memory) holds the weights and caches up to this window. Set --ctx-size to choose another.
Llama-3.2-3B F16, --ctx-size 131072 the same crash, after loading the weights fails at once: [GPUL-MEM-004] a context of 131072 tokens needs a key/value cache larger than one TornadoVM array can address; the most this model can hold is 74896 tokens. Pass --ctx-size 74896 or less (or leave it out to use the largest that fits).
Llama-3.2-1B F16, no --ctx-size starts starts with [server] context 131072 tokens (the model's own window) and answers
Gemma 4 E2B Q8_0, no --ctx-size starts at 131,072 tokens and answers starts at 119,808 tokens (one key/value array ... holds at most 119824 tokens of this model) and answers

To check:

./jitllm serve -m Llama-3.2-3B-Instruct-F16.gguf --gpu --port 8123
curl -s http://127.0.0.1:8123/v1/chat/completions -H 'Content-Type: application/json' \
  -d '{"messages":[{"role":"user","content":"Say hello in five words."}],"max_tokens":20}'
./jitllm serve -m Llama-3.2-3B-Instruct-F16.gguf --gpu --port 8123 --ctx-size 131072   # GPUL-MEM-004

Not covered

  • I ran it on Metal only; the arithmetic doesn't depend on the backend.
  • I didn't run continuous batching (--continuous-batching) end to end; its pooled bound is covered by the unit test.
  • For Gemma 4, the addressing bound is conservative: it assumes every layer is as wide as the widest. The memory budget doesn't limit Gemma 4 yet, because the memory prediction can't plan it (kvDim(), hiddenDim() and headSize()), and a model it can't plan is taken to fit. A follow-up PR adds Gemma 4's memory plan.

`jitllm serve -m Llama-3.2-3B-Instruct-F16.gguf --gpu` failed with
"Invalid number of elements (-536870912)": without --ctx-size the server
asked for the model's 131,072-token window, whose key/value array
(28 layers x 1024 x 131072 = 3.76e9 elements) exceeds what an int-indexed
TornadoVM array holds, and State.fillKvFields computed the size in an int
that wrapped negative.

- KeyValueAddressing: one place for the arithmetic (largest context a
  private or pooled key/value array can address).
- State.fillKvFields counts in long and refuses an overflow with the new
  [GPUL-MEM-004], naming the largest context that fits.
- LocalModels.largestFittingContext (@experimental) / MemoryPreflight: the
  model's own window, unless the array limit or the configured memory
  budget is shorter (a search over the metadata-only preflight), returned
  as a ContextFit that says which limit applied.
- serve: without --ctx-size it uses that and prints why. An explicit
  --ctx-size the cache cannot address fails with [GPUL-MEM-004] before any
  weight is read. Continuous batching uses the pooled bound.

Verified on an Apple M4 Pro (Metal): the 3B now starts with 36,864 tokens
and answers; --ctx-size 131072 gives the one-line error; Llama-3.2-1B
keeps its full 131,072-token window.
The context fit asked Configuration.kvDim(), which Gemma 4 refuses to
answer because its layers differ in width, so `jitllm serve` with a
Gemma 4 model failed at once with UnsupportedOperationException ("Gemma4
has per-layer head dimensions") where main serves it.

Configuration.keyValueAddressingWidth() is kvDim() for a model whose
layers share one width, and the widest layer for Gemma 4, which errs
towards a shorter context rather than an array that overflows. The fit
and serve's explicit-length check use it. Gemma 4 E2B Q8_0 now serves at
119,808 tokens and answers.
@stratika stratika mentioned this pull request Dec 1, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant