Skip to content

fix(cli): honor MLXCEL_PRINT_TOKEN_IDS on the OpenXLA generate path - #2980

Merged
inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/xla-print-token-ids
Nov 15, 2026
Merged

inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/xla-print-token-ids

Conversation

@Jaeyeong-CHOI

@Jaeyeong-CHOI Jaeyeong-CHOI commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

MLXCEL_PRINT_TOKEN_IDS was silently ignored on the OpenXLA backend. run_generate handles MLXCEL_BACKEND=xla in an early branch that returns before the shared tail where the ids are printed. This moves the two lines into print_token_ids_if_requested and calls it from both places.

Related issues

Self-contained CLI bug fix; no separate issue has been opened.

Type of change

  • feat — new user-visible feature
  • fix — bug fix
  • perf — performance improvement (include before/after numbers in the PR body)
  • refactor — internal restructuring without behavior change
  • chore — build, CI, dependencies, release infrastructure
  • docs — documentation only
  • test — tests only

What changed

  • src/commands/generate.rs: token_ids_line formats one line, print_token_ids_if_requested prints both when the variable is set. Called in the OpenXLA branch and in the shared tail, which are the only two places a generation result is printed.
  • src/commands/generate_tests.rs: token_ids_line_lists_the_count_then_the_ids pins the line format.
  • docs/environment-variables.md: the row says the variable applies on the OpenXLA backend, and that the prompt ids there are the text prompt's tokens before image or audio expansion.

The output format is unchanged: [prompt ids (N): a b c] and [token ids (N): a b c] on stderr.

Test plan

DGX Spark GB10 (sm_121, CUDA 13.0), IREE 3.12.0rc20260721, release build with --features cuda,xla-iree, mlx-community/Llama-3.2-1B-Instruct-4bit, -p "Explain in three sentences why the sky is blue." -n 24 --temp 0, MLXCEL_XLA_CONTEXT_CAPACITY=256.

run id lines on stderr
OpenXLA cuda, variable set, before this change 0
OpenXLA cuda, variable set, after 2
OpenXLA cuda, variable unset, after 0
MLX backend, variable set, after 2

Nothing is added to stdout in any of the four. The OpenXLA and MLX runs print the same 46 prompt ids and the same 24 generated ids for this prompt.

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets --features metal,accelerate -- -D warnings (not run; Linux host). cargo clippy --workspace --all-targets --features cuda -- -D warnings and cargo clippy --features cuda,xla-iree --bin mlxcel -- -D warnings are clean.
  • cargo test --workspace --profile test-fast --features metal,accelerate --no-fail-fast -- --test-threads=1 (not run; Linux host). cargo test --release --features cuda,xla-iree --bin mlxcel generate: 123 passed, 0 failed, 1 ignored.
  • cargo deny check (not run; no dependency change)
  • Validated with a real checkpoint (above)
  • If the change moves the numbers: not applicable

Also: python3 -m unittest discover -s tests -p 'test_*.py' (219 tests, OK), env-var docs, cross-repo refs, native env writes and license header checks.

Publication verification

Rebased onto 955335a3 before publication; git range-diff confirms the patch is unchanged. The GB10 generation, Rust tests and clippy results were obtained before this rebase. After rebasing, Python tooling ran 219 tests successfully on macOS (30 platform skips), and git diff --check passed.

Notes for reviewers

  • On the OpenXLA backend with images or audio the engine expands the prompt itself, so the printed prompt ids are the text prompt's tokens and not what the graph consumed. The docs row says so. The MLX path prints the same thing.
  • Only the cuda device was run. The change is in the CLI, before any device-specific code.

Checklist

  • PR title uses a Conventional Commits prefix (feat:, fix:, etc.)
  • One logical change per PR (split unrelated changes)
  • Updated docs/ if user-facing behavior or supported models changed
  • Updated // Used by: ... comments on any shared function I modified (see docs/code-guidelines.md)
  • No secrets, credentials, or .env files committed

`mlxcel generate` prints the prompt and generated token ids to stderr when
MLXCEL_PRINT_TOKEN_IDS is set, so two runs can be compared on ids rather
than on decoded text. The OpenXLA branch of run_generate returns before the
shared tail that prints them, so with MLXCEL_BACKEND=xla the variable was
silently ignored.

Move the two lines into print_token_ids_if_requested and call it from both
places. The lines keep their format; a unit test pins it.

On a DGX Spark GB10 (llama-3.2-1b-instruct-4bit, MLXCEL_XLA_DEVICE=cuda)
the same command prints no id line before this change and both lines after
it, nothing when the variable is unset, and the MLX backend's output is
unchanged.
@inureyes inureyes added priority:medium Medium priority status:review Under review type:bug Bug fixes, error corrections, or issue resolutions labels Nov 15, 2026
inureyes pushed a commit that referenced this pull request Nov 15, 2026
## Summary

`MLXCEL_XLA_QUANT=native` was inert on `MLXCEL_XLA_DEVICE=cuda`: the loader required the `hip` device, so the decode graph kept the f16-expanded weights. This ports the single-sequence native 4-bit GEMV to CUDA, as #2905 asks.

- `src/lib/mlxcel-xla/csrc/qmv4.cu`: the six single-sequence entry points of `csrc/qmv4.hip` (`qmv4_kernel`, `qmv4_row_kernel`, and the fused q/k/v and gate/up pairs from #2895), with one change, `__shfl_down_sync(0xffffffffu, ...)` for `__shfl_down(...)`. Same MLX affine layout, same ABI (i32 constants, read-only bindings, f32 outputs), `__half` activations and scales/biases.
- `src/lib/mlxcel-xla/build.rs`: compiles it with `nvcc` to `compute_80` PTX next to the Gemma3n kernel, in the same `IREE_CUDA_HOME` branch. PTX availability is now its own cfg, `xla_iree_cuda_ptx`, emitted only after both kernels compile; `xla_iree_cuda` keeps meaning "CUDA IREE runtime". Without `nvcc` the build prints a warning and carries no PTX instead of failing. A compiler that is found and rejects a source still fails the build.
- `src/lib/mlxcel-xla/src/native_qmv.rs`: embeds the PTX under `cfg(xla_iree_cuda_ptx)`, and builds the CUDA target alias (`#hal.executable.target<"cuda", "cuda-nvptx-fb">`) and the three `hal.executable.source` blocks from the same export tables the hip path uses.
- `src/lib/mlxcel-xla/src/iree.rs`: the switch now turns on for `cuda` as well as `hip`, and a graph that carries the PTX is compiled with `--iree-cuda-target=sm_80` (the flag the Gemma3n kernel already sets). The 4-bit group-64 gate, the signless `i32` packed operand and the LM head dtype check are the existing shared code.
- The emitter is unchanged apart from comments. The CUDA decode graph is the hip graph with the target alias and the embedded object swapped.
- Gemma3n: the code that needs its PTX (`gemma3n_qmv.rs`, the native SDPA gate and three test sections) moves from `cfg(xla_iree_cuda)` to `cfg(xla_iree_cuda_ptx)`. Gemma3n CUDA Q4 keeps its existing load-time error when the artifact is missing; it does not fall back to a numerically different path.
- `src/lib/mlxcel-xla/csrc/qmv4_cuda_oracle.cu`: a standalone check of the six exports against a host reference. It is not part of the build; the crate README has the two commands.

## Related issues

Closes #2905

## Type of change

- [ ] `feat` — new user-visible feature
- [ ] `fix` — bug fix
- [x] `perf` — performance improvement (include before/after numbers in the PR body)
- [ ] `refactor` — internal restructuring without behavior change
- [ ] `chore` — build, CI, dependencies, release infrastructure
- [ ] `docs` — documentation only
- [ ] `test` — tests only

## Measurements

DGX Spark GB10 (sm_121, CUDA 13.0, nvcc 13.0.88, driver 580.178.04), IREE 3.12.0rc20260721 from `scripts/iree/setup-cuda.sh`, release build with `--features cuda,xla-iree`, base `955335a3`. Greedy, `-n 128`, `MLXCEL_XLA_CONTEXT_CAPACITY=256`, warm vmfb, one process per run, two timed rounds after a warm-up round. Every number in this section is from the tree in this PR.

The premise first, measured before the port on `ce6855bc`: the switch does nothing on `cuda` (19.28 tok/s without it, 19.42 with it, same output, 48 tokens).

| checkpoint | prompt | f16-resident (tok/s) | native (tok/s) | output |
|---|---|---|---|---|
| llama-3.2-1b-instruct-4bit (tied) | 1 | 20.75, 20.18 | 58.41, 62.17 | identical |
| llama-3.2-1b-instruct-4bit (tied) | 2 | 20.19, 20.46 | 62.86, 69.20 | identical |
| Qwen2.5-7B-Instruct-4bit (untied) | 1 | 5.85, 5.87 | 19.04, 19.56 | identical |
| Qwen2.5-7B-Instruct-4bit (untied) | 2 | 5.76, 5.89 | 19.33, 19.02 | identical |

About 3.1x on llama-3.2-1b and 3.3x on Qwen2.5-7B. The native rounds on llama-3.2-1b spread more than the f16 ones (58.4 to 69.2); I did not find out why.

### Trace before and after

`nsys profile --trace=cuda`, llama-3.2-1b-instruct-4bit, prompt 1, 128 decode steps. Decode-step kernels are the ones whose launch count is a multiple of 128; prefill and one-off kernels are excluded (124.9 ms in the f16 run, 118.5 ms in the native run).

| | f16-resident | native |
|---|---|---|
| tok/s under `nsys` | 20.27 | 55.53 |
| launches per decode step | 309 | 309 |
| GPU kernel time per decode step | 41.81 ms | 8.28 ms |
| projection launches per step | 113 `vecmat` | 65 `qmv4_*` |
| projection kernel time per step | 39.57 ms | 5.96 ms |
| `batch_matmul` (attention), 32 per step | 1.89 ms | 1.89 ms |
| everything else | 164 launches, 0.35 ms | 212 launches, 0.43 ms |

Per kernel, f16 graph (name is out x in):

| kernel | per step | avg |
|---|---|---|
| `vecmat_2048x8192` (down) | 16 | 1093.5 us |
| `vecmat_8192x2048` (gate, up) | 32 | 303.0 us |
| `vecmat_2048x2048` (q, o) | 32 | 274.7 us |
| `vecmat_512x2048` (k, v) | 32 | 37.7 us |
| `vecmat_128256x2048` (head) | 1 | 2380.2 us |

Per kernel, native graph:

| kernel | per step | avg | per step total |
|---|---|---|---|
| `qmv4_gateup_kernel` | 16 | 175.0 us | 2.80 ms |
| `qmv4_kernel` (o, head) | 17 | 105.7 us | 1.80 ms |
| `qmv4_row_kernel` (down) | 16 | 46.9 us | 0.75 ms |
| `qmv4_qkv_kernel` | 16 | 38.5 us | 0.62 ms |

Two things differ from the gfx1151 picture in #2890 and #2907. The launch count does not fall: 113 projection launches become 65, and 48 small elementwise launches appear around the external dispatches. And the down projection is the largest single change, 1.09 ms per launch as an f16 `vecmat` against 47 us, which is more than the 4x byte reduction explains; the IREE-generated K=8192 reduction is slow on this device.

### Token identity

The four chat-prompt runs above produce identical text. On this base `mlxcel generate` does not print token ids on the XLA path (#2980 addresses that), so I also compared ids with the repository's own tools: `xla_traj_dump` for the f16 and the native trajectory (128 argmax steps, raw prompt, no EOS stop), and `xla_oracle_check` under `MLXCEL_XLA_QUANT=native` against the f16 dump.

| checkpoint | 128-token trajectories identical id for id |
|---|---|
| llama-3.2-1b-instruct-4bit | 6 of 6 |
| Qwen2.5-7B-Instruct-4bit | 5 of 6 |

The one mismatch is Qwen2.5-7B on "Write a short poem about a lighthouse keeper and the sea.", first differing at token 67 (f16 ` whisper`, native ` story`). What I checked:

- Both arms reproduce their own trajectory exactly on a second run.
- The XLA f32 path picks the f16 path's token.
- The MLX backend, fed the same 80-token prefix (the server's tokenization of it equals the prompt ids plus the first 67 generated ids), returns ` story` and reports the same log-probability for both candidates: -1.28125 and -1.28125, then ` challenge` at -2.328.

Position 67 is a tie at the resolution the MLX backend reports, consistent with sensitivity to arithmetic differences. This observation alone does not prove exact equality of the underlying logits or exclude every kernel defect: the native kernel dequantizes each weight in f32, where the f16 graph multiplies weights already rounded to f16. The README states identity as measured, not guaranteed, with this case.

## Builds without nvcc

`NVCC=/nonexistent/nvcc` with the CUDA IREE runtime installed, same host:

- `cargo test --release -p mlxcel-xla --features iree --lib`: 436 passed, 20 ignored. Two existing Gemma3n emitter tests assumed that a CUDA runtime implies the PTX; their native-only sections now sit behind the artifact cfg and the shared schema assertions still run.
- `cargo clippy -p mlxcel-xla --all-targets --features iree -- -D warnings` and `RUSTFLAGS="-D warnings" cargo check --features cuda,xla-iree`: clean, with the one `cargo:warning` that the PTX was omitted.
- Real run, llama-3.2-1b-instruct-4bit, "Explain in three sentences why the sky is blue.", 128 tokens, `xla_traj_dump`: the no-PTX binary produces the same token ids with the switch off and on, and with it on prints the fallback warning exactly once.
- A compiler that answers `--version` and then rejects the source (a fixture script exiting 23) fails the build with its diagnostic. It is not treated as an absent compiler.

The host keeps its already-built MLX CUDA dependencies, so this shows that the XLA PTX step is optional, not that the whole tree builds without a CUDA toolkit.

## Standalone kernel check

`csrc/qmv4_cuda_oracle.cu` launches the six exports directly, without IREE or a model, against an FP64 host reference: K from 64 to 18944 on both sides of the 4096 threshold, N of 1, 7, 8, 9 and 17, unequal fused output sizes, and guard slots after each output. On the GB10: 600 launches and 8440 outputs pass, the 300 launches with exactly representable inputs are exact, the largest absolute error on the rest is 1.19e-5 (0.019 of the FP32 error envelope), and `compute-sanitizer --tool memcheck` reports 0 errors.

This checks indexing and arithmetic of the kernels. It does not make the token comparison above 12 of 12.

## Acceptance criteria

| criterion from #2905 | result |
|---|---|
| Greedy output token-identical to the f16 path on llama-3.2-1b-instruct-4bit (tied) and one untied checkpoint, on two prompts | Met on the two chat prompts for both checkpoints (identical output, 128 tokens each). On raw-prompt id comparison: 6 of 6 on llama-3.2-1b, 5 of 6 on Qwen2.5-7B; the exception is the tie described above. |
| `xla_batch_bench` stays REFERENCE-EXACT | `--device cuda --batch 8 --requests 16 --maxcap 48`: `REFERENCE-EXACT PASS` with and without the switch (420 tokens). With the switch the single-sequence references come from the native path and the batch engine from f16 weights, so this is also an id-for-id match between the two on 16 requests. Batched throughput is unchanged (31.9 tok/s without, 32.4 with), and the single-sequence baseline the harness prints goes from 18.9 to 44.2 tok/s. |
| The f16 path, prefill, committed goldens and every non-CUDA device are unchanged | The f16 graph and prefill are not touched. The hip module builders now read the same export tables as CUDA, and the existing hip tests (`module_prefix_embeds_the_object_and_the_abi`, `decode_kinds_embed_only_their_own_exports`, the emitter's `native_decode_emits_the_packed_projection_dispatch`) pass unchanged; a new test holds the CUDA decode graph equal to the hip one apart from the alias and object. `cargo test -p mlxcel-xla --lib` passes with the committed goldens. Not run: any ROCm or Metal device (I have neither). |
| Trace before/after pasted: dispatch count, per-kernel time, tok/s at capacity 256, n=128 | Above. |
| Builds without nvcc still compile and keep the f16 path | Met. With `NVCC` pointing at a nonexistent path and the CUDA IREE runtime installed: `RUSTFLAGS="-D warnings" cargo check --features cuda,xla-iree` passes with one build warning, the XLA unit suite passes (436), and a real run with the switch on warns once, falls back, and produces the same 128 token ids as the f16 path. See "Builds without nvcc" below. |
| Tests and `cargo check --features xla-iree` under `RUSTFLAGS=-D warnings` stay clean | `RUSTFLAGS="-D warnings" cargo check --features cuda,xla-iree` is clean with and without `nvcc`. |

## Test plan

- [x] `cargo fmt --all -- --check`
- [ ] `cargo clippy --workspace --all-targets --features metal,accelerate -- -D warnings` (not run; Linux host). `cargo clippy -p mlxcel-xla --all-targets --features iree -- -D warnings` is clean with and without `nvcc`.
- [ ] `cargo test --workspace --profile test-fast --features metal,accelerate --no-fail-fast -- --test-threads=1` (not run; Linux host)
- [ ] `cargo deny check` (not run; no dependency change)
- [x] Validated with real checkpoints: `mlx-community/Llama-3.2-1B-Instruct-4bit`, `mlx-community/Qwen2.5-7B-Instruct-4bit`
- [x] Before/after numbers and environment are in the PR body

Also run on the GB10 host:

- `cargo test --release -p mlxcel-xla --lib`: 412 passed, 0 failed, 19 ignored (no IREE environment).
- `cargo test --release -p mlxcel-xla --features iree --lib`: 437 passed, 22 ignored (CUDA IREE build, PTX embedded); 436 passed, 20 ignored with `NVCC` pointing at a nonexistent path.
- `python3 -m unittest discover -s tests -p 'test_*.py'`: 219 tests, OK.
- Repository gates: env-var docs, binary assets, cross-repo refs, CUDA arch lists, kernel dtype keys, kernel port dispatch, license headers.

New unit tests:

- `cuda_kernels_are_the_hip_single_sequence_kernels`: `qmv4.cu` equals the corresponding `qmv4.hip` lines apart from the one intrinsic, so the two sources cannot drift.
- `cuda_kernel_source_matches_the_dispatch_contract`: the entry points and block geometry the dispatch constants assume.
- `cuda_module_parts_embed_the_ptx_under_the_cuda_target`: the CUDA module text equals the hip one with the object path swapped.
- `cuda_ptx_carries_every_single_sequence_entry` / `cuda_ptx_is_absent_without_a_compiled_artifact`: one per build configuration.
- `native_decode_graph_is_the_same_on_cuda_apart_from_the_embedded_object`: the emitted decode graph, 65 dispatches.

## Notes for reviewers

- **This changes what a CUDA IREE build without nvcc does, including for Gemma3n.** On `main` such a build fails in `build.rs`. Here it builds with a warning and no PTX. Dense models then keep the f16 path; Gemma3n CUDA Q4 fails at load with its existing "built without the CUDA-IREE PTX" error instead of at build time. I did this because the issue asks for builds without nvcc to compile. If you would rather keep the hard build failure for Gemma3n, the cfg split is the only part to revert.
- **Devices below sm_80.** The PTX is `compute_80` and the graph is compiled for `sm_80`, as for Gemma3n. I could not test what the opt-in switch does on an older device; I expect the module to fail to load rather than fall back.
- **Ragged engine.** Out of scope per the issue. On `cuda` the batch engine keeps the f16 weights whatever the switch says, and the multi-row exports stay hip-only.
- **Only the GB10 was measured.** No other NVIDIA device, and the hip path was not re-run. The kernel bodies are held line-for-line equal to the hip source by a test, but `nvcc` and `hipcc` may contract floating point differently, so I make no claim about cross-vendor bit equality.
- **The untied checkpoint is `Qwen2.5-7B-Instruct-4bit`**, not the `Qwen2.5-Coder-7B-Instruct-4bit` used in #2890. Same architecture and shapes (hidden 3584, down K=18944 on the row kernel).

## Checklist

- [x] PR title uses a Conventional Commits prefix (`feat:`, `fix:`, etc.)
- [x] One logical change per PR (split unrelated changes)
- [x] Updated `docs/` if user-facing behavior or supported models changed
- [x] Updated `// Used by: ...` comments on any shared function I modified (see `docs/code-guidelines.md`)
- [x] No secrets, credentials, or `.env` files committed
@inureyes

Copy link
Copy Markdown
Member

Implementation hardening for #2980.

Reviewed the PR purpose (no linked closing issue): both generation paths now share token-ID printing, with output preceding decode on XLA. The environment-disabled path avoids the extra formatting work. No additional correctness, security, or performance defect was found.

Validation: Token-ID formatting coverage and the CUDA CLI unit tests passed on the combined candidate tree; XLA model inference was not re-run for this formatting-only change.

Commands: cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1 on the combined candidate tree has passed the affected module tests noted above; the broader run is still finishing. cargo fmt --all -- --check and python3 scripts/ci/check_kernel_dtype_keys.py passed. Required GitHub checks are checked again immediately before merge.

@inureyes
inureyes merged commit eaed656 into lablup:main Nov 15, 2026
31 checks passed
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 15, 2026
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:medium Medium priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants