Repository navigation
Description
Problem / Background
Two defects share one cause: the OpenXLA path pins its sequence capacity at DEFAULT_CONTEXT_CAPACITY = 256 (src/lib/mlxcel-xla/src/context.rs:20) and never relates it to the request. The first defect makes the default CLI invocation unusable; the second refuses any long prompt.
The default CLI invocation fails. -n/--max-tokens defaults to -1 (src/cli/max_tokens.rs:19), resolve_cli_max_tokens (src/commands/generate.rs:336, called at src/commands/generate.rs:2988 inside run_generate_once) resolves that to context_window - prompt_len, and the OpenXLA branch passes the result to admission unchanged (src/commands/generate.rs:1743). On models/llama-3.2-1b-instruct-4bit (max_position_embeddings 131072) a 6-token prompt therefore asks for 131066 generated tokens and is refused before native execution:
OpenXLA generation failed: request exceeds the OpenXLA context capacity: effective_prompt_len=6 + max_new_tokens=131066 > context_capacity=256
Verified on the gfx1151 host with mlxcel generate -m models/llama-3.2-1b-instruct-4bit -p "The capital of France is" and no -n. This is the CLI analogue of #2848 finding 3, where the serve worker now clamps the admitted budget to the room the widest loaded shape leaves after prefill; the CLI has no equivalent clamp.
Long prompts fail too. With -n 1 and a 553-token prompt, admission sees 553 + 1 > 256 and refuses. MLX has no such static limit: the CLI sizes generation against the checkpoint's own window.
Why a flat larger default is not the fix
The capacity is also the sequence length every decode step attends over, and it grows KV memory linearly and the prefill attention mask quadratically (docs/environment-variables.md:462). Measured on gfx1151 with qwen2.5-0.5b-4bit, 5-token prompt, 64 greedy tokens, changing only the compiled capacity:
| capacity | tok/s | wall |
|---|---|---|
| 256 | 40.4 | 3 s |
| 512 | 40.3 | 3 s |
| 1024 | 39.3 | 3 s |
| 2048 | 35.8 | 4 s |
| 4096 | 29.5 | 12 s |
| 8192 | 15.5 | 13 s |
A 4096 static shape costs about 27% on this model and about 9 s of extra startup. llama-3.2-1b-instruct-4bit is flat across 512 to 2048 (10.2 to 10.9 tok/s), so the cost is model-dependent and no single global default is right. In-tree Molmo2 4B data (src/lib/mlxcel-xla/src/batch.rs:522) shows the same direction: 3.18 tok/s at 256, 2.17 at 1024, 1.41 at 2048. That is why the fix sizes the shape from the request and keeps a floor rather than raising the floor.
Current Behavior
- CLI:
XlaBackend::create_sessioncallsmlxcel_xla::context_capacity_from_env()(src/backend/xla.rs:115-116) and never sees the request. Its only caller isgenerate_xla(src/commands/generate.rs:1592, invoked fromsrc/commands/generate.rs:3129), which holds bothprompt_tokensand the resolvedmax_tokensbefore creating the session atsrc/commands/generate.rs:1610. - Server:
src/server/model_worker.rs:1502derives buckets withcontext_capacity_buckets_from_env(image_floor).derive_context_buckets(src/lib/mlxcel-xla/src/context.rs:122) returns[256]whenimage_floorisNone, which is every text-only checkpoint, so serving rejects both classes of request as well. - Docs:
docs/environment-variables.md:462-463records both defaults.
Proposed Solution
-
Ladder, budget, and resolver in
mlxcel-xla. Add tosrc/lib/mlxcel-xla/src/context.rs:pub const CONTEXT_CAPACITY_LADDER: [usize; 8] = [256, 512, 1024, 2048, 4096, 8192, 16384, 32768];pub const DEFAULT_XLA_GENERATION_BUDGET: usize = 512;pub const SERVER_TEXT_CONTEXT_CAPACITY: usize = 4096;pub fn resolve_context_capacity(required_positions: Option<usize>, model_window: Option<usize>) -> Result<usize, String>. Rule, in order: a setMLXCEL_XLA_CONTEXT_CAPACITYwins and yields exactly one shape, as today; aNonehint yieldsDEFAULT_CONTEXT_CAPACITY; otherwiseceiling = model_window.unwrap_or(32768).min(32768), arequired_positionsaboveceilingis an error (see Error handling), and the result ismin(smallest ladder entry >= required_positions, ceiling). Because the ceiling check runs first, the result always admits the request, and a checkpoint window below the ladder minimum yields the window itself.- Re-export all four from
src/lib/mlxcel-xla/src/lib.rs:184-186.
-
CLI sizes the shape from the request and clamps the admitted budget. Add a defaulted
ComputeBackend::create_session_for_request(&self, model_path, num_layers, kv_cache_mode, token_bias, required_positions: Option<usize>) -> Result<Session>besidecreate_session(src/backend/mod.rs:150), whose default body callsself.create_session(...), plus the matchingBackenddispatch besidesrc/backend/mod.rs:283; MLX, the experimental scaffold, and every existing caller and test then stay unchanged.XlaBackendoverrides it (src/backend/xla.rs:96) to callresolve_context_capacity(required_positions, mlxcel::read_model_context_window(model_path)); that reader already preferstext_configover the top level (src/loading/mod.rs:569,context_window_from_configatsrc/loading/mod.rs:588). Inrun_generate_once, capture the requested value before line 2988 and computesizing_budget = if requested == UNLIMITED_MAX_TOKENS { DEFAULT_XLA_GENERATION_BUDGET.min(max_tokens) } else { max_tokens }, so the default-n -1sizes on 512 rather than on the whole window.generate_xlathen useseffective_hint = prompt_tokens.len() + image_paths.len() * mlxcel::xla_image_context_floor(model_path).unwrap_or(0)and passesrequired_positions = effective_hint + sizing_budget, saturating, tocreate_session_for_request. After the session exists, replace everymax_tokenspassed to a generation call withadmitted = max_tokens.min(capacity.saturating_sub(effective_hint)), read fromXlaInferenceSession::context_capacity()(src/lib/mlxcel-xla/src/lib.rs:520), which is the same clamp fix: harden the OpenXLA continuous-batching engine after #469 #2848 finding 3 applies on the serve path. An explicit-n Nis unaffected because the chosen capacity already admitseffective_hint + N. Print one line after session creation whenMLXCEL_XLA_CONTEXT_CAPACITYis unset, in the style of the existingMax tokens: unlimited (-1) -> ...notice (src/commands/generate.rs:346-348):OpenXLA context capacity: <capacity> for <effective_hint> prompt + up to <admitted> generated tokens (request-sized; MLXCEL_XLA_CONTEXT_CAPACITY pins one shape). -
Server derives a serving bucket bounded by the model. Change
context_capacity_buckets_from_env(image_floor)tocontext_capacity_buckets_from_env(image_floor, model_window)andderive_context_buckets(src/lib/mlxcel-xla/src/context.rs:122) toderive_context_buckets(text_default, model_window, image_floor), returning the sorted, deduplicated union of[text_default, min(SERVER_TEXT_CONTEXT_CAPACITY, model_window.unwrap_or(SERVER_TEXT_CONTEXT_CAPACITY))]plusimage_floorwhen it is larger. The caller atsrc/server/model_worker.rs:1502passescrate::read_model_context_window(&model_path). So a text-only checkpoint with a large window serves[256, 4096], a checkpoint with a 2048 window serves[256, 2048], and a VLM with a 1834 floor serves[256, 1834, 4096]. Update the tests atsrc/lib/mlxcel-xla/src/context.rs:229-236. Routing is already "smallest bucket that admits prompt plus generation budget" (route_capacity,src/lib/mlxcel-xla/src/batch.rs:507-517), so short requests keep the 256 shape and the second shape costs one extra graph compile and its resident memory.MLXCEL_XLA_CONTEXT_BUCKETS=256restores the old set without a code change. -
Docs: update both rows at
docs/environment-variables.md:462-463for the ladder, the 512 default generation budget, the request-sized CLI shape, and the window-bounded server set.
Rejected alternative: adding required_positions to create_session itself. That forces an edit to every implementation and test for a hint only the OpenXLA backend consumes, while the defaulted method leaves the MLX path byte-identical.
Scope
In scope: src/lib/mlxcel-xla/src/context.rs, src/lib/mlxcel-xla/src/lib.rs, src/backend/mod.rs, src/backend/xla.rs, src/commands/generate.rs, src/server/model_worker.rs, docs/environment-variables.md.
Out of scope: audio expansion in the sizing hint and in the clamp (data-dependent and known only after tokenization, so audio requests keep today's admission behavior and need their own issue); changing the non-XLA paths; graph shape changes; paged or chunked KV.
Implementation Notes
- Reuse:
read_model_context_window/context_window_from_configfor the window,xla_image_context_floorfor image expansion,route_capacityfor server routing, and the fix: harden the OpenXLA continuous-batching engine after #469 #2848 clamp shape on the CLI. Do not add a second config reader. - Constraints: a pinned capacity and a pinned bucket list keep byte-identical behavior, including the single-shape rule and the image guard. The ladder maximum stays under the IREE signed 32-bit position limit already documented in
src/lib/mlxcel-xla/src/context.rs:43-46. Do not remove the existingresolve_cli_max_tokensbehavior for MLX; it still resolves-1against the window there. - Edge cases:
max_tokens = 0sizes on the prompt alone; a required length between rungs takes the next rung; a window below 256 yields the window; a checkpoint with no readable window falls back to the 4096DEFAULT_CONTEXT_WINDOW_FALLBACKpath for the budget and to the 32768 rung for the ceiling; an image request on a family without a floor formula adds nothing to the hint and still fails at admission when it does not fit, which is current behavior; a prompt that leaves no generation room still fails with the capacity error. - Error handling: a request above the window or above the ladder maximum fails before any graph compiles, with
this request needs <required> positions but the checkpoint context window is <window>; shorten the prompt or lower -n, or with the ladder maximum named when no window is readable. No silent clamping of the prompt itself; only the generation budget is clamped, and only downward to the room the chosen shape has.
Acceptance Criteria
-
mlxcel generate -m models/llama-3.2-1b-instruct-4bit -p "The capital of France is"with no-nand no capacity variable succeeds on XLA, reportsOpenXLA context capacity: 1024for 6 prompt tokens plus up to 1018 generated tokens, and stops at EOS or that room. - The same prompt with
-n 64reportsOpenXLA context capacity: 256, so the fast floor is still what short explicit requests compile. (With the 512 default budget the no--ncase lands on 1024 by construction; 6 + 512 = 518.) - A 553-token prompt with
-n 1reportsOpenXLA context capacity: 1024, and with no-nreports 2048 (553 + 512 = 1065). - An explicit
-n 2000reportsOpenXLA context capacity: 2048and is not clamped below 2000. - A prompt plus budget beyond the model window is rejected before a graph compiles, with the required positions and the window named.
- A text-only checkpoint served over OpenXLA gets
capacities=[256, 4096]in the worker start log (src/server/model_worker.rs:1526-1531), serves a prompt that does not fit 256, and still routes a short request to 256; a checkpoint with a 2048 window gets[256, 2048]. -
MLXCEL_XLA_CONTEXT_CAPACITYstill produces exactly one shape and ignores the request;MLXCEL_XLA_CONTEXT_BUCKETSstill overrides the derived set. - Unit tests cover ladder selection (1, 256, 257, 518, 1065, 32768), the window cap (including a window below 256 and a required length above the window), the 512 default budget, the derived bucket set with and without a window and an image floor, the admission clamp, and the CLI hint arithmetic including one image.
-
docs/environment-variables.mdupdated andmake verify-env-var-docspasses. - All of it in one PR, with one local gate at the end and minimal pushes.
Verification
cargo test -p mlxcel-xla
cargo test --features xla-backend --lib
make verify-rocmManual check on the gfx1151 host, after make iree-rocm prints the toolchain environment and cargo build --release --features xla-iree:
MLXCEL_BACKEND=xla MLXCEL_XLA_DEVICE=hip MLXCEL_XLA_ROCM_TARGET=gfx1151 \
./target/release/mlxcel generate --model models/llama-3.2-1b-instruct-4bit -p "The capital of France is"A pass is a completed generation with the capacity line above and no capacity variable set. Repeat with -n 64 and expect 256, with a 553-token prompt and -n 1 and expect 1024, with -n 2000 and expect 2048, then with a prompt longer than the checkpoint window and expect the named error and no compile.
Technical Considerations
Builds on #857 (capacity parameterization), #861 (image admission), #1271 / #1272 (bucket derivation and image floors), and #2848 finding 3 (the serve-path budget clamp this mirrors on the CLI). #1271 already settled that a text shape and an image shape coexist; this issue makes the text shape reachable for long prompts and for the default -n case.
Activity
[-]fix(xla): the 256-token default context capacity rejects prompts every other backend accepts[/-][+]fix(xla): context-capacity defaults refuse long prompts and the default -n budget on the CLI[/+]fix(xla): gate the unlimited-budget probe behind the XLA feature
fix(xla): size the static context shape from the request (#2856)