Repository navigation
fix(xla): harden the ragged batch-engine residuals - #2936
Conversation
A positive rope_delta could push an M-RoPE decode coordinate to or past context_capacity, and the ragged graph indexes the [context_capacity, rot] RoPE table with it, so the gather became an out-of-bounds device read at a library boundary rather than an error the graph could report.
mrope_decode_coordinate now takes the capacity and returns a typed OutOfRange { coordinate, context_capacity } error naming both values at and past the bound. DecodePositionState carries the capacity, mrope_slot_coordinates threads it through the ragged engine, and both the single-sequence and ragged decode paths reject before any FFI call. The C ragged validator also rejects an out-of-range M-RoPE coordinate so a direct C caller cannot bypass the bound.
Tests: decode_coordinate_rejects_at_the_context_capacity_boundary and mrope_slot_coordinates_reject_at_and_past_context_capacity cover capacity - 1, capacity, and capacity + delta on both sides of the bound; the existing signed-delta and overflow tests stay green.
Refs #2923
xla_ensure_batch_kv calloc'd a full rank-5 [B,L,S,nkv,d] f32 host buffer and uploaded it twice through xla_alloc_bv, so the first admit after a reset moved about 512 MiB per cache from host memory at B=4 and capacity 2048. Allocate each device-local cache directly and zero it with a queue-ordered iree_hal_device_queue_fill (a 4-byte zero pattern) awaited on a fence semaphore before the buffer view is published. No host allocation the size of the cache and no host-to-device copy remain in this path. The existing overflow checks and the release-both-then-NULL failure cleanup are unchanged. Test: first_batch_admit_does_not_upload_a_host_kv_mirror, a real-device root test, resets shim counters that record any host mirror or upload performed inside this path and asserts both stay zero across a full request. The counters are compiled only under the test-support feature. Refs #2923
The ragged decode graph's [B,...] shapes are fixed when decode_ragged_logits_b{b_max} is emitted, but xla_ctx recorded no compiled B and xla_llama_ragged_reset accepted any positive bsz. A direct C caller could therefore reset at a different size and fail later as an opaque graph shape mismatch inside IREE.
Add an additive xla_llama_ragged_bind(ctx, compiled_b) that records the emit-time batch size, call it in IreeRaggedLlama::load_inner immediately after context creation for both the base and bucket contexts, and rebuild before the first reset. Reset now rejects an unbound context and bsz != compiled_b with both values in the message. The existing reset signature is unchanged, so the spike/iree-ffi callers need no update.
Test: ragged_reset_rejects_a_batch_size_the_graph_was_not_compiled_for binds B=8 and asserts reset(4) and reset-before-bind both fail, then binds B=4 and asserts reset(4) still succeeds.
Refs #2923
A prefill slot store writes K and then V with two device-to-device transfers, so a failure or cancellation between them left the slot's KV visibly half-written and the ragged decode would read a torn prompt as if the slot were live. The store now clears the slot's validity byte before the first transfer and sets it only after both complete, and the ragged decode validator rejects any row that is active on an invalid slot, naming the row, slot, token and cache_len. Inactive rows stay exempt because the engine encodes a free slot as an all-zero row. ragged_reset allocates fresh flags so a reset never inherits validity from the previous batch, and the test-support build exposes a hook that fails the V transfer plus a validity accessor. Test: failed_slot_store_leaves_the_slot_invalid_and_decode_rejects_it, a real-device root test, tampers with the store, asserts the slot stays invalid and the active decode is rejected before IREE runs, then re-stores and requires the decode to match the single-sequence reference. Refs #2923
The startup image guard judges the requested capacity set before any engine is built, so it can pass and the bucket load can still drop the image-capable shape, leaving image requests to fail at admission behind a generic dropped-bucket warning. xla_image_surviving_bucket_warning re-evaluates the floor against the capacities that actually compiled, and the worker logs the result at startup. It stays a warning because text serving is unaffected and dropped-bucket tolerance is deliberate. Tests: four unit tests cover dropping the only image-capable capacity, a surviving image-capable bucket, dropping a smaller text-only bucket, and the no-floor plus nothing-requested-above-the-floor cases. Refs #2923
The crate's own unit-test binary cannot link the IREE runtime, the same constraint documented for route_capacity, so the new bound's ragged test cannot run there. This adds an ignored root test that loads a tiny Qwen2 M-RoPE checkpoint into IreeRaggedLlama, asserts a coordinate at context_capacity is rejected by the Rust guard with both values named, and asserts a coordinate one below the bound reaches the graph rather than being over-rejected. Refs #2923
No behavior change: the formatter's layout for the new M-RoPE error variants, the test-support re-exports and counter tuple, and the moved test call. Refs #2923
The C validator reports the invalid slot on stderr and the Rust wrapper surfaces only the FFI status, so the assertion now checks that the wrapper failed and then re-runs the identical row after a successful store. That retry succeeding proves the earlier rejection was the slot validity check rather than a shape error. Refs #2923
xla_batch_bench only exercised greedy requests through one XlaBatchEngine, so a bucket set's non-largest shapes, a seeded non-greedy sampler and cancellation mid-stream had no reference gate. Three optional modes now cover them: --buckets loads an XlaBucketSet, adds a prompt sized to route into each requested bucket and asserts every bucket routes and matches its reference; --seed runs the same non-greedy seeded workload twice, requires identical streams and requires top_k=1 to equal the greedy reference; --cancel cancels admitted requests after their first token, requires no later event for them and requires every non-cancelled stream to stay reference-exact while later requests reuse the slots. A shared GateEngine trait drives both engine types, request ids are mapped back to submission rows because a bucket set namespaces them, and any mismatch exits non-zero. Verified on ROCm: the default greedy gate at B=4, the seeded and cancel modes at B=4 and B=8, and a two-bucket 256/2048 run all print their pass lines. Refs #2923
The plain `xla-iree` feature compile that CI runs with `cargo check --features cuda,xla-iree --all-targets` builds every integration test without the root `test-utils` feature. The new gate imports `IreeRaggedLlama` and the batch-KV counters, which exist only under mlxcel-xla's `test-support` feature, so the job failed with E0432 before the linker was reached. Gate the file on both features, as `tests/xla_gemma3n_prefill.rs` already does for `xla-iree`. Refs #2923
`scripts/ci/check_env_var_docs.py` scans every `MLXCEL_*` token under `src/`, so the `MLXCEL_XLA_TEST_SUPPORT` C preprocessor macro that the mlxcel-xla build script passes to `build.define` was read as an undocumented environment variable and failed both the env-var-docs job and its repository test. It is a build-internal define, not an operator setting, so allowlist it with that reason instead of documenting it on the environment page. Refs #2923
The M-RoPE coordinate guard added for issue #2923 covered the Rust callers and the ragged C validator, but the single-sequence C decode entry points (xla_llama_decode and xla_llama_decode_mrope) still checked positions only for negativity. A direct C caller, which is an untrusted library boundary, could pass a position at or past context_capacity and reach IREE with an out-of-range coordinate, bypassing the Rust guard. xla_llama_decode_impl now rejects a position at or past context_capacity, naming the axis, the coordinate and the capacity, and checks the context, position and output pointers for NULL before dereferencing them. Valid inputs are unchanged: both Rust decode paths reject out-of-range coordinates before the call, and the single-sequence path passes pos = cache_len, which is already bounded below the capacity. Verified with cargo check -p mlxcel-xla --features iree --lib (exit 0, the shim compiles) and the narrow boundary unit tests decode_coordinate and mrope_slot_coordinates (all pass). Refs #2923.
|
Security review of the #2923 hardening. Fixed in 7ba1d6a: the M-RoPE coordinate upper bound was enforced in the Rust decode paths and the ragged C validator, but the single-sequence C entry points ( Verified: Remaining observation, not introduced by this PR and outside item 2's decode scope: the single-sequence and slot prefill entries ( |
The `MLXCEL_XLA_CONTEXT_BUCKETS` row now describes the startup warning added for issue #2923: a capacity after the first that fails to load is dropped, and if the surviving set no longer reaches the checkpoint's worst-case image floor the worker warns instead of failing startup, because text serving still works. Operators who set this variable are the readers who need to know an image-capable shape can disappear after the pre-load guard has passed. Validation: `python3 scripts/ci/check_env_var_docs.py` and `python3 -m unittest tests/test_check_env_var_docs.py` both exit 0. Refs #2923
* fix(xla): bound prefill positions in the C entry points A prefill position outside [0, context_capacity) is an out-of-bounds device read, not an error the graph can report: the emitted graph indexes the RoPE table with the caller values and clamps nothing, and the padded tail (real_len < lp) reaches the same gather. PR #2936 bounded decode at the Rust wrapper and the C decode entry points; the four prefill C entry points still forwarded caller positions unchecked. Add one shared xla_check_prefill_positions helper and call it before any IREE call from xla_llama_prefill, xla_llama_prefill_slot_logits, xla_llama_prefill_diagnostics_slot, and xla_llama_prefill_embeddings_impl, covering every axis and every padded-tail slot. xla_llama_prefill also NULL-checks its context, tokens, positions, and output; the diagnostics entry gains the token/position NULL checks. The first violation returns 1 and prints the caller, axis, index, value, and capacity. The public Rust API synthesizes canonical positions and rejects explicit out-of-range ones before C, so two test-support forwarders drive the boundary directly. One device test feeds an out-of-range 1D position and an out-of-range M-RoPE axis through the same tokens that succeed when every value is in range. Validated with cargo fmt, clippy -D warnings on mlxcel-xla, the registered-golden test (no golden edited), a test-target check, and the full ignored xla_ragged_hardening suite on the ROCm host (5 passed). Closes #2954 * docs: add technical report for PR #2957
Split the ragged load span into module load and weight upload through the existing MLXCEL_XLA_LOAD_TIMING reporter. The parts line now carries the uploaded tensor count, bytes, host dequantize time, f16 pack time and device copy time. A capacity bucket reports zero upload because it shares the base context's views. No new labels are printed when the variable is unset. Add test-support counters for xla_llama_upload_weight and an ignored root device test that asserts one upload per declared weight spec and none for a capacity bucket. xla_batch_bench loads the engine before its timed window again. #2936 (311ad93) moved the load under t_run while replacing the pump loop with drive, which is what dropped the f16 B=4 reading from the control's 63.4 tok/s to 20.8 and made the #2933 targets look unverifiable. The pre-#2933 control (fd2a65e) loads the same span in 4.9 s on the same checkpoint, host, IREE distribution and capacity, so the 0.7 s figure in the issue does not reproduce. The f16 ragged load is the host dequantize, f16 pack and 3.0 GB device copy, unchanged from the control, and flat across capacity 256 and 1024. Measured on gfx1151, medians of three runs: f16 ragged load 5.62 s at B=4 and 5.03 s at B=8, native 1.17 s and 1.15 s. Decode-only medians are 64.0 and 60.4 tok/s for f16 and 61.7 and 75.8 for native at B=4 and B=8.
…#2976) * fix(xla): split ragged load timing, restore decode-only tok/s (#2961) Split the ragged load span into module load and weight upload through the existing MLXCEL_XLA_LOAD_TIMING reporter. The parts line now carries the uploaded tensor count, bytes, host dequantize time, f16 pack time and device copy time. A capacity bucket reports zero upload because it shares the base context's views. No new labels are printed when the variable is unset. Add test-support counters for xla_llama_upload_weight and an ignored root device test that asserts one upload per declared weight spec and none for a capacity bucket. xla_batch_bench loads the engine before its timed window again. #2936 (311ad93) moved the load under t_run while replacing the pump loop with drive, which is what dropped the f16 B=4 reading from the control's 63.4 tok/s to 20.8 and made the #2933 targets look unverifiable. The pre-#2933 control (fd2a65e) loads the same span in 4.9 s on the same checkpoint, host, IREE distribution and capacity, so the 0.7 s figure in the issue does not reproduce. The f16 ragged load is the host dequantize, f16 pack and 3.0 GB device copy, unchanged from the control, and flat across capacity 256 and 1024. Measured on gfx1151, medians of three runs: f16 ragged load 5.62 s at B=4 and 5.03 s at B=8, native 1.17 s and 1.15 s. Decode-only medians are 64.0 and 60.4 tok/s for f16 and 61.7 and 75.8 for native at B=4 and B=8. * docs: report the ragged load timing split (#2961)
Summary
Closes #2923. This hardens the six ragged continuous-batching residuals grouped in the issue from the #469 audit: the lazy rank-5 batch KV is zeroed on the device instead of through a host mirror, M-RoPE decode coordinates are bounded by the compiled capacity before any IREE call, a ragged reset refuses a batch size the graph was not compiled for, a prefill KV store marks a slot valid only after both transfers land,
examples/xla_batch_bench.rsgains bucket, seeded-sampling and cancellation modes, and startup warns when the surviving bucket set no longer has an image-capable shape.The changes are committed per item. No performance work is folded in, and the FFI additions are additive (
xla_llama_ragged_bindtakes the compiled B; no existing signature changed).Items
1. Batch KV zeroing without a host mirror (
d9bbabdb)Before this change
xla_ensure_batch_kv_innerlazily allocated the rank-5 cache bycallocing a host mirror and uploading it with a host-to-device transfer on first admit, which costs4*B*L*S*nkv*dbytes of host memory plus a full H2D copy per bucket.Now
xla_alloc_zeroed_bvallocates the device buffer and zeroes it withiree_hal_device_queue_fillfollowed by a semaphore wait, and test-only counters record the host and H2D bytes that the lazy path spends.Gate:
first_batch_admit_does_not_upload_a_host_kv_mirrorintests/xla_ragged_hardening.rssubmits a request, pumps to idle, and asserts both counters are zero. The counters arrive with the change so the removed path can be observed; that path always took the calloc plus upload route and cannot report zero.2. M-RoPE coordinate upper bound (
4b7cd7ca, device gatecf6d3a0d, C entry-point guard7ba1d6a2)Before this change both decode paths computed
coordinate = cache_len + rope_deltaand indexed the[context_capacity, rot]RoPE table with no upper bound. A coordinate equal to the capacity is an out-of-bounds device read, not an error the graph can report.Now
mrope_decode_coordinateandmrope_slot_coordinatesreturn a typedMropeCoordinateError::OutOfRange { coordinate, context_capacity }(andNegative) before any IREE call. The C shim repeats the upper-bound check at both the ragged decode validator and the single-sequencexla_llama_decode/xla_llama_decode_mropeentry points, so a direct C caller cannot bypass the Rust guard.Gates:
decode_coordinate_rejects_at_the_context_capacity_boundaryanddecode_coordinate_supports_signed_deltas_and_typed_failuresinmlxcel-xla,mrope_slot_coordinates_reject_at_and_past_context_capacityinbatch.rs, and the real-deviceragged_mrope_decode_rejects_a_coordinate_at_the_context_capacity. The device test asserts that a coordinate at the capacity is rejected with a message naming the bound and the capacity, and that a coordinate one below it is not rejected by that guard, so the bound does not over-reject.3. Ragged reset must match the compiled batch size (
7cb73243)Before this change reset cleared state for any
bsz, so a mismatch surfaced later as an opaque graph shape failure inside IREE.Now load binds the compiled B before the reset (
xla_llama_ragged_bind), andxla_llama_ragged_resetrejects an unbound context orbsz != rg_compiled_b, naming both values.Gate:
ragged_reset_rejects_a_batch_size_the_graph_was_not_compiled_forasserts that reset at a mismatched B and reset before any bind both return nonzero, while a reset matching the bound compiled B still succeeds. Note that the unbound half is rejected byxla_llama_ragged_binditself, so the mismatched-B case is the one that exercises the reset comparison.4. A slot stays invalid until both KV transfers land (
42d807b5, assertion fix9d907220)Before this change the slot store transferred K and then V, so a failed V transfer left resident K behind and decode read a half-written slot.
Now
rg_valid[slot]is cleared before the K transfer and set only after both transfers succeed.xla_llama_decode_ragged_implrejects an active row whose slot is invalid withrow=%d slot=%d token=%d cache_len=%d is active but its KV slot is not valid.Gate:
failed_slot_store_leaves_the_slot_invalid_and_decode_rejects_ituses the test hook to fail the V transfer, asserts the slot is invalid, asserts the decode call fails through the C validator, then stores the same prompt successfully, re-decodes the identical row, and compares two decoded tokens againstXlaReferenceEngine. The Rust wrapper surfaces onlyxla_llama_decode_ragged_logits failed (status 1); the validator message goes to stderr, which the suite prints.5. Bench modes for buckets, seeding and cancel (
0e0dadc8)Before this change the bench exercised only
XlaBatchEnginewith greedy sampling.Now
--buckets c1,c2,...drives anXlaBucketSetwith one routing-coverage request per capacity,--seed Nwith--temperatureand--top-pruns two independent seeded engines and checks determinism plus atop_k=1pass against the greedy references, and--cancel Ncancels N admitted requests after their first token and requires no later event for them. Request ids are mapped through aHashMap<u64, usize>because a bucket set namespaces ids per bucket, so the submission index is not the id.Gate: the bench itself is the gate. It prints
BUCKETS REFERENCE-EXACT PASS,SEEDED SAMPLING PASSandCANCEL PASS, and exits nonzero on a mismatch.6. Startup warning when surviving buckets lose the image shape (
26fb5055, docs31787aee)Before this change the pre-load image guard judged the requested capacities. If the only image-capable bucket then failed to load, nothing warned and image requests were refused later at admission with no startup signal.
Now, after
XlaBucketSet::load,xla_image_surviving_bucket_warning(&engine.capacities(), &capacities, image_floor)warns when the requested set had an image-capable bucket, no surviving bucket reaches the floor, and something was actually dropped. The warning names the dropped capacities, the largest surviving capacity, the floor andMLXCEL_XLA_CONTEXT_CAPACITY.docs/environment-variables.mdnow describes the drop and warning behavior forMLXCEL_XLA_CONTEXT_BUCKETS.Gates: four unit tests in
src/multimodal/host_preprocessor_tests.rscover a dropped image bucket, a surviving image bucket, a dropped smaller bucket with an image bucket still surviving, and the no-floor or no-image-capable-request cases.Changes during review
a93ca23agatestests/xla_ragged_hardening.rsbehindxla-iree,test-utils, so the plainxla-iree--all-targetscompile that CI runs does not try to resolve the test-support-only imports.a4b112f1allowlists the build-internalMLXCEL_XLA_TEST_SUPPORTC define inscripts/ci/check_env_var_docs.py, because it is abuild.definefor the shim, not an operator environment variable.7ba1d6a2adds the same coordinate upper bound to the single-sequence C decode entry points and NULL-checks their pointers, closing the direct-C-caller bypass that the ragged-only guard left open.31787aeedocuments the bucket-drop image warning indocs/environment-variables.md.Verification
Environment: AMD Strix Halo (gfx1151) through ROCm, pinned IREE ROCm distribution
iree-rocm-3.12.0rc20260721, devicehip. Every cargo and GPU command ran throughscripts/rocm_gpu_guard.sh --hold -- bash -lc '...'withOPENSSL_INCLUDE_DIR=/usr/include,OPENSSL_LIB_DIR=/usr/lib/x86_64-linux-gnu,IREE_ROCM_HOMEset andeval "$(scripts/iree/setup-rocm.sh --env)", capped atCARGO_BUILD_JOBS=8.Final real-device hardening suite (the
#[ignore]gates, matching thetests/xla_prepared_prefill.rspattern because the crate's own unit-test binary cannot link the IREE runtime):Result: 4 passed, 0 failed, exit 0. The stderr lines show the item 4 validator rejecting
row=0 slot=0 token=7 cache_len=3, and the item 3 reset rejectingbsz=4againstcompiled_b=8.Compile, lint and format gates after the review commits:
All exit 0. The clippy output contains only vendored IREE C header warnings.
Unit and tooling gates:
Results: 3 passed, 1 passed, 29 passed (1 ignored), the env-var docs check exits 0, and 214 python tooling tests pass.
Bench modes, on the generated tiny llama checkpoint (no real checkpoint is present on this host; the fixture matches the one
tests/xla_ragged_hardening.rsbuilds, so this proves reference-exactness, not throughput):Result:
RESULT: REFERENCE-EXACT PASS,BENCH ... pass=true.Result:
RESULT: REFERENCE-EXACT PASS,BUCKETS REFERENCE-EXACT PASS,SEEDED SAMPLING PASS (deterministic=true, top_k=1==greedy=true),CANCEL PASS (2/2 cancelled, non-cancelled requests reference-exact=true).The same extended flags at
--batch 4 --requests 8 --maxcap 24also passed all three checks, and--buckets 256,2048passedBUCKETS REFERENCE-EXACT PASSwith both capacities routed.Notes
The
mlxcel-xlaunit-test binary cannot link the IREE runtime, so the M-RoPE, slot-validity, compiled-B and batch-KV gates live in the root crate undertests/xla_ragged_hardening.rsand are#[ignore]d for ordinary CI, following the existingtests/xla_prepared_prefill.rsconvention. The boundary arithmetic is additionally unit tested without IREE.The security review noted one pre-existing, out-of-scope gap:
xla_llama_prefillandxla_llama_prefill_slot_logitsbound token counts but not position values, so a direct C caller can still hand an out-of-range prefill position to IREE. It is tracked in a PR comment and belongs in a follow-up; changing four prefill entry points would broaden this PR.