Repository navigation
feat(xla): compile a set of context capacities and route requests between them - #1302
Merged
Merged
Conversation
…ween them The OpenXLA context capacity is a static graph shape and is also the sequence length every decode step attends over, so it trades image capability against text throughput and no single value wins. Measured on the pinned Molmo2 4B checkpoint: 3.18 tok/s at capacity 256, 2.17 at 1024, 1.41 at 2048, while one image on that checkpoint expands to between 424 and 1834 tokens. Serving images therefore meant running every text request on the image-sized shape. The engine now holds one compiled shape per capacity and routes each request to the smallest that admits it. Measured on the same checkpoint with buckets [256, 1834], text-only decode runs at 3.190, 3.155 and 3.198 tok/s across three repeats, indistinguishable from the single-256 baseline, while an image request succeeds in the same process. The four design questions the issue left open, and what was chosen: Bucket selection is derived from the checkpoint: the text default plus the worst-case image expansion when one is known. MLXCEL_XLA_CONTEXT_CAPACITY still yields exactly one bucket, because pinning a capacity is an existing operator decision that must keep producing the engine it produced before buckets existed. MLXCEL_XLA_CONTEXT_BUCKETS takes an explicit list. Compile and memory cost is dominated by weights, not by shapes. A 4B model widened to f32 is roughly 16 GB while a bucket's own KV cache at capacity 256 is about 0.30 GB, so buckets share the uploaded weights and only duplicate KV. Sharing is by refcount rather than by borrowing: a bucket retains the instance, the device and every weight buffer view, so the existing free path releases exactly what it retained and the base and its buckets have no lifetime ordering between them. A bucket after the first that fails to compile or allocate is dropped with its reason logged, because the remaining shapes still serve every request that fits them. Batching does not span buckets. Each has its own graph and its own KV cache, so rows in different buckets cannot advance together and pump drives every non-empty bucket in turn. Slots are therefore per bucket rather than pooled, which is the price of not promoting every text request to the image shape. Migration as a sequence grows is not implemented because it cannot arise. A request is routed on its prompt plus its whole generation budget, the same invariant single-shape admission already enforced, so a request that fits at admission cannot outgrow its shape later. Admitting on prompt length alone and migrating on growth was the alternative; it would require copying KV between differently shaped caches and was rejected because conservative admission costs nothing the single-shape path did not already cost. Two defects found while building this are worth naming. Each scheduler issued request ids from zero, so two buckets would hand the same id to different requests and the server, which matches cancellations and completions by id, would have acted on the wrong one rather than failing visibly; ids now stride by the bucket count so an id names its own bucket. And the bucket context first copied has_deepstack and has_prefill_diagnostics from its base, but those flags decide which modules are appended and which entry points are probed, so a base carrying a diagnostics bundle would have made a bucket append a module the caller never passed; they are derived from the arguments and cross-checked against the base instead.
Recorded before the merge, per the TECHNICAL_REPORTS/.keep-reports contract.
10 of 11 tasks
inureyes
added a commit
that referenced
this pull request
Aug 22, 2026
…1381) ## Summary The `xla-compile` job denied `unused_imports` rather than `warnings` because the `cuda,xla-iree` and `xla-diagnostics` feature sets carried a dead-code and clippy backlog that would have made the job red the day it landed. This clears that backlog and widens the gate to `-D warnings`. Resolution followed the criterion in the issue: cfg-gate to the feature set that has a real consumer where the gate needs no duplicate definition, otherwise allow with a comment naming the caller, and delete only when a search finds no consumer under any feature combination. ## What changed ### `mlxcel-xla` - `src/lib/mlxcel-xla/src/iree.rs`: `IreeRaggedLlama::decode_ragged_logits` is now `#[cfg(feature = "diagnostics")]`. Its only callers are `LlavaReferenceDiagnosticEngine::capture` and the Gemma3n diagnostic runners in `batch.rs`, all of which are already `#[cfg(feature = "diagnostics")]`; serving calls `decode_ragged_logits_with_modes` directly. - `src/lib/mlxcel-xla/src/iree.rs`: `decode_ragged_mrope_logits` is deleted. This is the one deletion in the PR. `grep -rn "decode_ragged_mrope_logits" . --exclude-dir=.git --exclude-dir=target` filtered of the `_with_modes` sibling and the `xla_llama_` extern returns exactly two hits: the definition itself, and an error-message string inside `decode_ragged_mrope_logits_with_modes` that stays. There is no caller in any crate, test, bench, or example, under any feature combination. - `src/lib/mlxcel-xla/src/iree.rs`: a doc comment describing `create_ctx` had been stranded above a blank line when #1302 inserted `create_bucket_ctx` and its own doc block between them, which is what `clippy::empty_line_after_doc_comments` was reporting. It is moved back onto `create_ctx`. - `src/lib/mlxcel-xla/src/aux.rs`: `AuxiliaryWeightDType::Float16` and `Uint32` are allowed under `not(feature = "micro-oracle")`. `numeric_probe.rs`, behind that feature, is their only construction site, while `ffi_code` and `size_bytes` have to keep mapping them for the FFI contract on every build. Gating the variants themselves would force a `cfg` onto each arm of those two matches, including the `Float32 | Uint32` arm. - `src/lib/mlxcel-xla/src/phi4_audio.rs`: `load_audio_module` takes a scoped `#[allow(clippy::too_many_arguments)]`. A parameter struct would ripple into both call sites for a private single-file helper, so the allow was preferred per the issue's guidance. - `src/lib/mlxcel-xla/src/aux_manifest.rs`: the nested `if let` in `cache_lock_is_stale` collapses to an edition-2024 let chain. ### `mlxcel` - `src/server/batch/xla_audio_preprocess.rs`: the test-only surface is allowed under `not(test)`, following the `#[cfg_attr(not(test), allow(dead_code))]` pattern already used in `src/model_metadata.rs` and `src/server/startup.rs`. Each site names `xla_audio_preprocess_tests.rs` as the caller: `AudioPreprocessStage::spawn` (serving uses `spawn_with_loader` to keep MLX handles thread-confined), `recv` (serving must not block, so it drains with `try_recv`), `metrics`, `is_healthy`, the `healthy` field it reads, `AudioPreprocessMetrics::snapshot`, and `AudioPreprocessMetricsSnapshot`. The `Cancelled(AudioPreprocessCheckpoint)` payload keeps its field with the same allow: serving matches it as `Cancelled(_)`, and the checkpoint distinction belongs in the type because `Cancelled` is constructed at several checkpoints in that file. - `src/server/media.rs`: `validate_xla_raw_counts` gains a `not(test)` arm alongside its existing `not(feature = "xla-iree")` one. `media_tests.rs` is its only caller; the XLA admission path calls `validate_xla_raw_counts_with_audio` directly because it knows whether the loaded family supports audio. - `src/server/batch/xla_worker_admission.rs`: `drain_preprocessed` takes `#[allow(clippy::while_let_loop)]`. The suggested `while let Some(stage) = self.image_preprocessor.as_ref()` head holds a shared borrow of `self` across a body that calls `&mut self` methods and clears the field, so the `match` shape is load-bearing rather than stylistic. - `src/loading/vlm.rs` and `src/models/sanitize.rs`: the two `needless_match` sites take `#[cfg_attr(not(feature = "surgery"), allow(clippy::needless_match))]`. The match only collapses to `match transform { Some(t) => Some(t), None => None }` when the `surgery` arm is compiled out, which is why the lint fires under `--no-default-features` and not under the default feature set. Applying clippy's suggestion would delete active-pipeline resolution from the default build, so the lint is silenced only for the builds that see the collapsed shape. ### CI - `.github/workflows/ci.yml`: `xla-compile` now sets `RUSTFLAGS: "-D warnings"`, and the paragraph explaining the narrower `-D unused_imports` policy is replaced. - `.github/workflows/ci.yml`: the "Deliberately NOT covered" list records the gap that remains after this change. The job runs `cargo check`, so `-D warnings` denies rustc lints only. `dead_code` and `unused_imports` are gated now, but `collapsible_if`, `needless_match`, `too_many_arguments`, `while_let_loop` and the rest of clippy's own lints are still gated by nothing in CI under these feature sets, because the `clippy` job covers default features only. That half of the backlog can regrow silently; swapping this job's `cargo check` for `cargo clippy` was deliberately left out of scope. ## No runtime behavior change The diff is attribute additions, `cfg` additions, comments, one collapsed `if`, one doc-comment move, and the deletion of one function that has no caller. No executed code path changes. ## Test plan Run on the GB10 host with the IREE runtime provisioned (`bash scripts/iree/setup-cuda.sh`, `eval "$(bash scripts/iree/setup-cuda.sh --env)"`, `MLX_CUDA_ARCHITECTURES=121`), and re-run on the final commit after the review follow-ups landed. Acceptance criteria: - [x] `cargo clippy --features cuda,xla-iree --all-targets -- -D warnings`: exit 0, no warnings. - [x] `cargo clippy --no-default-features --features xla-diagnostics --all-targets -- -D warnings`: exit 0, no warnings. - [x] Default-feature regression, `cargo clippy -p mlxcel --lib --tests -- -D warnings`: exit 0, no warnings. The two commands the job itself runs, under the widened flag, because `cargo clippy -- -D warnings` applies the flag only to the primary package while `RUSTFLAGS` reaches every path-built unit including `mlxcel-core` and `mlxcel-surgery`. Clippy passing is therefore not sufficient evidence that the job will be green: - [x] `RUSTFLAGS="-D warnings" cargo check --features cuda,xla-iree --all-targets`: exit 0. - [x] `RUSTFLAGS="-D warnings" cargo check --no-default-features --features xla-diagnostics --all-targets`: exit 0. Scoped and mechanical checks: - [x] `cargo clippy -p mlxcel-xla --lib --features iree --all-targets -- -D warnings` - [x] `cargo clippy -p mlxcel-xla --lib --features iree,diagnostics --all-targets -- -D warnings` - [x] `cargo clippy -p mlxcel-xla --lib --features iree,micro-oracle --all-targets -- -D warnings`, confirming the `micro-oracle` cfg arm on the `AuxiliaryWeightDType` variants is not narrowed wrongly - [x] `rustfmt --edition 2024 --check` on every changed Rust file - [x] `.github/workflows/ci.yml` parses as YAML End to end, this PR's own CI exercises the change it makes: `OpenXLA feature compile` ran for 7m44s under the new `RUSTFLAGS: "-D warnings"` and passed, so the widened gate is green on arrival rather than red. `OpenXLA feature link`, added by #1305, also ran because `src/lib/mlxcel-xla/**` is in its path filter. Not verified: - [ ] `metal,accelerate`. It cannot be built on this Linux host, so it is unverified by execution rather than confirmed. The static argument that it is unaffected: `make verify-clippy` runs `--features metal,accelerate` without `--no-default-features`, so `surgery` stays on and both `needless_match` attributes expand to nothing; `mlxcel-xla` builds with no features there, so `iree.rs`, `aux.rs`, `aux_manifest.rs` and `phi4_audio.rs` sit behind `#[cfg(feature = "iree")]` and never compile; and on the `mlxcel` side only `media.rs` and `xla_audio_preprocess.rs` compile, where every change is an `allow` attribute that cannot break a build. ## Follow-ups this surfaced, out of scope here - `mlxcel-xla`'s `#[cfg(test)]` modules are gated by no CI job at all. There is no `default-members`, so `cargo check` in this job resolves to `-p mlxcel` and `--all-targets` expands within that package only, while the `clippy` job builds default features where `mlxcel-xla` is default-off. Recorded in the workflow's exclusion list. - Clippy-only lints under these feature sets remain ungated, so that half of the backlog can regrow. Closing it means running clippy in this job, which was left out of scope deliberately. - `media_tests.rs` reaches `validate_xla_raw_counts_with_audio` only through the `supports_audio = false` wrapper, so the `true` branch has no direct unit coverage, and the sign of that flag is the security-relevant bit. Closes #1304
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…ween them (lablup#1302) * feat(xla): compile a set of context capacities and route requests between them The OpenXLA context capacity is a static graph shape and is also the sequence length every decode step attends over, so it trades image capability against text throughput and no single value wins. Measured on the pinned Molmo2 4B checkpoint: 3.18 tok/s at capacity 256, 2.17 at 1024, 1.41 at 2048, while one image on that checkpoint expands to between 424 and 1834 tokens. Serving images therefore meant running every text request on the image-sized shape. The engine now holds one compiled shape per capacity and routes each request to the smallest that admits it. Measured on the same checkpoint with buckets [256, 1834], text-only decode runs at 3.190, 3.155 and 3.198 tok/s across three repeats, indistinguishable from the single-256 baseline, while an image request succeeds in the same process. The four design questions the issue left open, and what was chosen: Bucket selection is derived from the checkpoint: the text default plus the worst-case image expansion when one is known. MLXCEL_XLA_CONTEXT_CAPACITY still yields exactly one bucket, because pinning a capacity is an existing operator decision that must keep producing the engine it produced before buckets existed. MLXCEL_XLA_CONTEXT_BUCKETS takes an explicit list. Compile and memory cost is dominated by weights, not by shapes. A 4B model widened to f32 is roughly 16 GB while a bucket's own KV cache at capacity 256 is about 0.30 GB, so buckets share the uploaded weights and only duplicate KV. Sharing is by refcount rather than by borrowing: a bucket retains the instance, the device and every weight buffer view, so the existing free path releases exactly what it retained and the base and its buckets have no lifetime ordering between them. A bucket after the first that fails to compile or allocate is dropped with its reason logged, because the remaining shapes still serve every request that fits them. Batching does not span buckets. Each has its own graph and its own KV cache, so rows in different buckets cannot advance together and pump drives every non-empty bucket in turn. Slots are therefore per bucket rather than pooled, which is the price of not promoting every text request to the image shape. Migration as a sequence grows is not implemented because it cannot arise. A request is routed on its prompt plus its whole generation budget, the same invariant single-shape admission already enforced, so a request that fits at admission cannot outgrow its shape later. Admitting on prompt length alone and migrating on growth was the alternative; it would require copying KV between differently shaped caches and was rejected because conservative admission costs nothing the single-shape path did not already cost. Two defects found while building this are worth naming. Each scheduler issued request ids from zero, so two buckets would hand the same id to different requests and the server, which matches cancellations and completions by id, would have acted on the wrong one rather than failing visibly; ids now stride by the bucket count so an id names its own bucket. And the bucket context first copied has_deepstack and has_prefill_diagnostics from its base, but those flags decide which modules are appended and which entry points are probed, so a base carrying a diagnostics bundle would have made a bucket append a module the caller never passed; they are derived from the arguments and cross-checked against the base instead. * docs(reports): add the technical report for lablup#1302 Recorded before the merge, per the TECHNICAL_REPORTS/.keep-reports contract.
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…ablup#1381) ## Summary The `xla-compile` job denied `unused_imports` rather than `warnings` because the `cuda,xla-iree` and `xla-diagnostics` feature sets carried a dead-code and clippy backlog that would have made the job red the day it landed. This clears that backlog and widens the gate to `-D warnings`. Resolution followed the criterion in the issue: cfg-gate to the feature set that has a real consumer where the gate needs no duplicate definition, otherwise allow with a comment naming the caller, and delete only when a search finds no consumer under any feature combination. ## What changed ### `mlxcel-xla` - `src/lib/mlxcel-xla/src/iree.rs`: `IreeRaggedLlama::decode_ragged_logits` is now `#[cfg(feature = "diagnostics")]`. Its only callers are `LlavaReferenceDiagnosticEngine::capture` and the Gemma3n diagnostic runners in `batch.rs`, all of which are already `#[cfg(feature = "diagnostics")]`; serving calls `decode_ragged_logits_with_modes` directly. - `src/lib/mlxcel-xla/src/iree.rs`: `decode_ragged_mrope_logits` is deleted. This is the one deletion in the PR. `grep -rn "decode_ragged_mrope_logits" . --exclude-dir=.git --exclude-dir=target` filtered of the `_with_modes` sibling and the `xla_llama_` extern returns exactly two hits: the definition itself, and an error-message string inside `decode_ragged_mrope_logits_with_modes` that stays. There is no caller in any crate, test, bench, or example, under any feature combination. - `src/lib/mlxcel-xla/src/iree.rs`: a doc comment describing `create_ctx` had been stranded above a blank line when lablup#1302 inserted `create_bucket_ctx` and its own doc block between them, which is what `clippy::empty_line_after_doc_comments` was reporting. It is moved back onto `create_ctx`. - `src/lib/mlxcel-xla/src/aux.rs`: `AuxiliaryWeightDType::Float16` and `Uint32` are allowed under `not(feature = "micro-oracle")`. `numeric_probe.rs`, behind that feature, is their only construction site, while `ffi_code` and `size_bytes` have to keep mapping them for the FFI contract on every build. Gating the variants themselves would force a `cfg` onto each arm of those two matches, including the `Float32 | Uint32` arm. - `src/lib/mlxcel-xla/src/phi4_audio.rs`: `load_audio_module` takes a scoped `#[allow(clippy::too_many_arguments)]`. A parameter struct would ripple into both call sites for a private single-file helper, so the allow was preferred per the issue's guidance. - `src/lib/mlxcel-xla/src/aux_manifest.rs`: the nested `if let` in `cache_lock_is_stale` collapses to an edition-2024 let chain. ### `mlxcel` - `src/server/batch/xla_audio_preprocess.rs`: the test-only surface is allowed under `not(test)`, following the `#[cfg_attr(not(test), allow(dead_code))]` pattern already used in `src/model_metadata.rs` and `src/server/startup.rs`. Each site names `xla_audio_preprocess_tests.rs` as the caller: `AudioPreprocessStage::spawn` (serving uses `spawn_with_loader` to keep MLX handles thread-confined), `recv` (serving must not block, so it drains with `try_recv`), `metrics`, `is_healthy`, the `healthy` field it reads, `AudioPreprocessMetrics::snapshot`, and `AudioPreprocessMetricsSnapshot`. The `Cancelled(AudioPreprocessCheckpoint)` payload keeps its field with the same allow: serving matches it as `Cancelled(_)`, and the checkpoint distinction belongs in the type because `Cancelled` is constructed at several checkpoints in that file. - `src/server/media.rs`: `validate_xla_raw_counts` gains a `not(test)` arm alongside its existing `not(feature = "xla-iree")` one. `media_tests.rs` is its only caller; the XLA admission path calls `validate_xla_raw_counts_with_audio` directly because it knows whether the loaded family supports audio. - `src/server/batch/xla_worker_admission.rs`: `drain_preprocessed` takes `#[allow(clippy::while_let_loop)]`. The suggested `while let Some(stage) = self.image_preprocessor.as_ref()` head holds a shared borrow of `self` across a body that calls `&mut self` methods and clears the field, so the `match` shape is load-bearing rather than stylistic. - `src/loading/vlm.rs` and `src/models/sanitize.rs`: the two `needless_match` sites take `#[cfg_attr(not(feature = "surgery"), allow(clippy::needless_match))]`. The match only collapses to `match transform { Some(t) => Some(t), None => None }` when the `surgery` arm is compiled out, which is why the lint fires under `--no-default-features` and not under the default feature set. Applying clippy's suggestion would delete active-pipeline resolution from the default build, so the lint is silenced only for the builds that see the collapsed shape. ### CI - `.github/workflows/ci.yml`: `xla-compile` now sets `RUSTFLAGS: "-D warnings"`, and the paragraph explaining the narrower `-D unused_imports` policy is replaced. - `.github/workflows/ci.yml`: the "Deliberately NOT covered" list records the gap that remains after this change. The job runs `cargo check`, so `-D warnings` denies rustc lints only. `dead_code` and `unused_imports` are gated now, but `collapsible_if`, `needless_match`, `too_many_arguments`, `while_let_loop` and the rest of clippy's own lints are still gated by nothing in CI under these feature sets, because the `clippy` job covers default features only. That half of the backlog can regrow silently; swapping this job's `cargo check` for `cargo clippy` was deliberately left out of scope. ## No runtime behavior change The diff is attribute additions, `cfg` additions, comments, one collapsed `if`, one doc-comment move, and the deletion of one function that has no caller. No executed code path changes. ## Test plan Run on the GB10 host with the IREE runtime provisioned (`bash scripts/iree/setup-cuda.sh`, `eval "$(bash scripts/iree/setup-cuda.sh --env)"`, `MLX_CUDA_ARCHITECTURES=121`), and re-run on the final commit after the review follow-ups landed. Acceptance criteria: - [x] `cargo clippy --features cuda,xla-iree --all-targets -- -D warnings`: exit 0, no warnings. - [x] `cargo clippy --no-default-features --features xla-diagnostics --all-targets -- -D warnings`: exit 0, no warnings. - [x] Default-feature regression, `cargo clippy -p mlxcel --lib --tests -- -D warnings`: exit 0, no warnings. The two commands the job itself runs, under the widened flag, because `cargo clippy -- -D warnings` applies the flag only to the primary package while `RUSTFLAGS` reaches every path-built unit including `mlxcel-core` and `mlxcel-surgery`. Clippy passing is therefore not sufficient evidence that the job will be green: - [x] `RUSTFLAGS="-D warnings" cargo check --features cuda,xla-iree --all-targets`: exit 0. - [x] `RUSTFLAGS="-D warnings" cargo check --no-default-features --features xla-diagnostics --all-targets`: exit 0. Scoped and mechanical checks: - [x] `cargo clippy -p mlxcel-xla --lib --features iree --all-targets -- -D warnings` - [x] `cargo clippy -p mlxcel-xla --lib --features iree,diagnostics --all-targets -- -D warnings` - [x] `cargo clippy -p mlxcel-xla --lib --features iree,micro-oracle --all-targets -- -D warnings`, confirming the `micro-oracle` cfg arm on the `AuxiliaryWeightDType` variants is not narrowed wrongly - [x] `rustfmt --edition 2024 --check` on every changed Rust file - [x] `.github/workflows/ci.yml` parses as YAML End to end, this PR's own CI exercises the change it makes: `OpenXLA feature compile` ran for 7m44s under the new `RUSTFLAGS: "-D warnings"` and passed, so the widened gate is green on arrival rather than red. `OpenXLA feature link`, added by lablup#1305, also ran because `src/lib/mlxcel-xla/**` is in its path filter. Not verified: - [ ] `metal,accelerate`. It cannot be built on this Linux host, so it is unverified by execution rather than confirmed. The static argument that it is unaffected: `make verify-clippy` runs `--features metal,accelerate` without `--no-default-features`, so `surgery` stays on and both `needless_match` attributes expand to nothing; `mlxcel-xla` builds with no features there, so `iree.rs`, `aux.rs`, `aux_manifest.rs` and `phi4_audio.rs` sit behind `#[cfg(feature = "iree")]` and never compile; and on the `mlxcel` side only `media.rs` and `xla_audio_preprocess.rs` compile, where every change is an `allow` attribute that cannot break a build. ## Follow-ups this surfaced, out of scope here - `mlxcel-xla`'s `#[cfg(test)]` modules are gated by no CI job at all. There is no `default-members`, so `cargo check` in this job resolves to `-p mlxcel` and `--all-targets` expands within that package only, while the `clippy` job builds default features where `mlxcel-xla` is default-off. Recorded in the workflow's exclusion list. - Clippy-only lints under these feature sets remain ungated, so that half of the backlog can regrow. Closing it means running clippy in this job, which was left out of scope deliberately. - `media_tests.rs` reaches `validate_xla_raw_counts_with_audio` only through the `supports_audio = false` wrapper, so the `true` branch has no direct unit coverage, and the sign of that flag is the security-relevant bit. Closes lablup#1304
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The OpenXLA context capacity is a static graph shape and is also the sequence length every decode step attends over, so it trades image capability against text throughput. Measured on the pinned Molmo2 4B checkpoint: 3.18 tok/s at capacity 256, 2.17 at 1024, 1.41 at 2048, while one image on that checkpoint expands to between 424 and 1834 tokens. Serving images meant running every text request on the image-sized shape.
The engine now compiles one shape per capacity and routes each request to the smallest that admits it.
Text-only decode is indistinguishable from the single-256 baseline across three repeats while an image request succeeds in the same process, which is the combination a single shape could not produce.
The four design questions, and the rejected alternatives
Bucket selection is derived from the checkpoint: the text default plus the worst-case image expansion when
xla_image_context_floorknows one.MLXCEL_XLA_CONTEXT_CAPACITYstill yields exactly one bucket, because pinning a capacity is an existing operator decision that has to keep producing the engine it produced before buckets existed.MLXCEL_XLA_CONTEXT_BUCKETStakes an explicit list for an operator who knows their traffic better than a derivation can.Compile and memory cost is dominated by weights, not by shapes, which is what makes this affordable at all. A 4B model widened to f32 is roughly 16 GB, while a bucket's own KV cache at B_max 4 is about 0.30 GB at capacity 256 against 2.42 GB at 2048. So buckets share the uploaded weights and duplicate only KV: the marginal cost of adding a small text bucket next to an image bucket is 0.30 GB, not 16 GB.
Sharing is by refcount rather than by borrowing. A bucket retains the instance, the device and every weight buffer view, so the existing
xla_llama_freereleases exactly what the bucket retained, needs no special case, and the base and its buckets have no lifetime ordering between them. The alternative, a "borrowed" flag with a conditional free, was rejected because it makes correctness depend on an ordering nothing enforces.A bucket after the first that fails to compile or to allocate is dropped with its reason logged rather than failing the process, because the remaining shapes still serve every request that fits them. The first bucket failing is fatal, since nothing has loaded to fall back to.
Batching does not span buckets. Each has its own compiled graph and its own KV cache, so rows in different buckets cannot be advanced together;
pumpdrives every non-empty bucket in turn. Slots are therefore per bucket rather than pooled, which is the honest price of not promoting every text request to the image shape.Migration as a sequence grows is not implemented, because it cannot arise. A request is routed on its prompt plus its whole generation budget, the same invariant single-shape admission already enforced, so a request that fits at admission cannot outgrow its shape later. Admitting on prompt length alone and migrating on growth was the alternative; it would require copying KV between differently shaped caches, and it was rejected because conservative admission costs nothing the single-shape path did not already cost. This is the design question that dissolved rather than being answered, and the unit tests pin the invariant that makes it dissolve.
Two defects found while building this
Both are the kind a compiler does not catch, and both would have failed quietly rather than loudly.
Request ids collided across buckets. Each scheduler issued ids from zero, so two buckets would hand the same id to different requests. The server matches cancellations and completion events by id, so the collision would have cancelled or completed the wrong request rather than erroring. Ids now stride by the bucket count, which makes them unique and makes an id name its own bucket, so
cancelneeds no side table that could drift.The bucket context copied the wrong two flags.
has_deepstackandhas_prefill_diagnosticsdecide which modules get appended to a session and which entry points are probed. Copying them from the base meant a base carrying a diagnostics bundle would make a bucket try to append a module the caller never passed. They are derived from the arguments now, exactly as the owning create path does, and a deepstack mismatch against the base is rejected explicitly, since the shared weights are read under the base's contract.Validation
cargo test -p mlxcel-xla --lib batch::(21 passed), covering smallest-admitting-bucket selection, routing on the whole budget rather than the prompt, rejection above the largest bucket, single-bucket equivalence, and id non-collisioncargo test -p mlxcel-xla --lib context::(8 passed), covering the derived set, an explicit list, and the admission invariant that makes migration unnecessarycargo check --features cuda --all-targets,cargo check --features cuda,xla-iree --all-targets,cargo check --no-default-features --features xla-diagnostics --all-targets, all cleancapacities=[256, 1834]derived from the Molmo2 checkpoint, both shapes compiled, server up, three-repeat throughput above, and a correct image answer from the same processThe routing rule is a pure function over capacities, separate from the engine, because this crate's own tests cannot link the IREE runtime. That is the same reason
Schedulerwas split out, and it keeps the selection rule testable without a device.Closes #1271