Skip to content

fix(xla): context-capacity defaults refuse long prompts and the default -n budget on the CLI #2855

Closed

Description

@inureyes

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_session calls mlxcel_xla::context_capacity_from_env() (src/backend/xla.rs:115-116) and never sees the request. Its only caller is generate_xla (src/commands/generate.rs:1592, invoked from src/commands/generate.rs:3129), which holds both prompt_tokens and the resolved max_tokens before creating the session at src/commands/generate.rs:1610.
  • Server: src/server/model_worker.rs:1502 derives buckets with context_capacity_buckets_from_env(image_floor). derive_context_buckets (src/lib/mlxcel-xla/src/context.rs:122) returns [256] when image_floor is None, which is every text-only checkpoint, so serving rejects both classes of request as well.
  • Docs: docs/environment-variables.md:462-463 records both defaults.

Proposed Solution

  1. Ladder, budget, and resolver in mlxcel-xla. Add to src/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 set MLXCEL_XLA_CONTEXT_CAPACITY wins and yields exactly one shape, as today; a None hint yields DEFAULT_CONTEXT_CAPACITY; otherwise ceiling = model_window.unwrap_or(32768).min(32768), a required_positions above ceiling is an error (see Error handling), and the result is min(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.
  2. 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> beside create_session (src/backend/mod.rs:150), whose default body calls self.create_session(...), plus the matching Backend dispatch beside src/backend/mod.rs:283; MLX, the experimental scaffold, and every existing caller and test then stay unchanged. XlaBackend overrides it (src/backend/xla.rs:96) to call resolve_context_capacity(required_positions, mlxcel::read_model_context_window(model_path)); that reader already prefers text_config over the top level (src/loading/mod.rs:569, context_window_from_config at src/loading/mod.rs:588). In run_generate_once, capture the requested value before line 2988 and compute sizing_budget = if requested == UNLIMITED_MAX_TOKENS { DEFAULT_XLA_GENERATION_BUDGET.min(max_tokens) } else { max_tokens }, so the default -n -1 sizes on 512 rather than on the whole window. generate_xla then uses effective_hint = prompt_tokens.len() + image_paths.len() * mlxcel::xla_image_context_floor(model_path).unwrap_or(0) and passes required_positions = effective_hint + sizing_budget, saturating, to create_session_for_request. After the session exists, replace every max_tokens passed to a generation call with admitted = max_tokens.min(capacity.saturating_sub(effective_hint)), read from XlaInferenceSession::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 N is unaffected because the chosen capacity already admits effective_hint + N. Print one line after session creation when MLXCEL_XLA_CONTEXT_CAPACITY is unset, in the style of the existing Max 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).

  3. Server derives a serving bucket bounded by the model. Change context_capacity_buckets_from_env(image_floor) to context_capacity_buckets_from_env(image_floor, model_window) and derive_context_buckets (src/lib/mlxcel-xla/src/context.rs:122) to derive_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))] plus image_floor when it is larger. The caller at src/server/model_worker.rs:1502 passes crate::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 at src/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=256 restores the old set without a code change.

  4. Docs: update both rows at docs/environment-variables.md:462-463 for 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_config for the window, xla_image_context_floor for image expansion, route_capacity for 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 existing resolve_cli_max_tokens behavior for MLX; it still resolves -1 against the window there.
  • Edge cases: max_tokens = 0 sizes 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 4096 DEFAULT_CONTEXT_WINDOW_FALLBACK path 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 -n and no capacity variable succeeds on XLA, reports OpenXLA context capacity: 1024 for 6 prompt tokens plus up to 1018 generated tokens, and stops at EOS or that room.
  • The same prompt with -n 64 reports OpenXLA context capacity: 256, so the fast floor is still what short explicit requests compile. (With the 512 default budget the no--n case lands on 1024 by construction; 6 + 512 = 518.)
  • A 553-token prompt with -n 1 reports OpenXLA context capacity: 1024, and with no -n reports 2048 (553 + 512 = 1065).
  • An explicit -n 2000 reports OpenXLA context capacity: 2048 and 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_CAPACITY still produces exactly one shape and ignores the request; MLXCEL_XLA_CONTEXT_BUCKETS still 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.md updated and make verify-env-var-docs passes.
  • 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-rocm

Manual 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

  1. added
    type:bug
    area:inference
    priority:high
    status:in-progress
    on Nov 5, 2026
  2. changed the title [-]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[/+] on Nov 5, 2026
  3. added this to the 0.9 milestone on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:inferencepriority:highstatus:in-progresstype:bug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions