Skip to content

ROCm packed attention: leave the compiled block when varlen is refused instead of attending over the dense mask - #18435

Merged
danielhanchen merged 2 commits into
mainfrom
kp-rocm-block-varlen
Nov 19, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
kp-rocm-block-varlen

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Follow-up to #18393. On ROCm builds where torch's flash varlen cannot run inside a compiled graph (its fake kernel declares a logsumexp of another rank, seen on gfx1151 with torch 2.11), packed rows in a compiled decoder block now leave the block and run the eager varlen wrapper. Before this change they stayed in the block and attended with SDPA over the dense [T, T] mask, while HF_PACKED_ATTENTION_STATS["compiled"] counted them as varlen.

Root cause

_block_varlen_prepare (unsloth/utils/hf_packed_attention.py) returned (cu_seqlens, carrier) without asking whether the varlen op can run in the graph. Inside the block, _varlen_in_graph then returned False, _leaves_block is always False on ROCm (it only targets slow cuDNN plans on CUDA), so the call ended at the wrapped orig(...): dense SDPA inside the compiled block. Before #18393 that block failed to compile and the stock eager forward ran varlen, so on ROCm #18393 traded a graph break for dense attention (#18313 measured dense SDPA at 98.5 ms vs 11 ms for varlen at 2048 tokens).

Fix

On ROCm only, for fp16 / bf16 rows with head dim up to 256, _block_varlen_prepare asks _varlen_in_graph (the same cached probe the traced call uses). When it refuses, it returns _LEAVE_BLOCK, as the int32 overflow branch already does, so _sdpa_packed_varlen calls the eager wrapper (torch.compiler.disable), which runs torch's varlen op. These rows are no longer counted as compiled. CUDA builds, ROCm builds whose varlen traces, and fp32 rows keep the current route.

Tests

New tests/test_hf_packed_attention_rocm_leave_block.py (CPU, ROCm faked through torch.version.hip, probes stubbed):

  • ROCm with the in-graph probe refusing: block_varlen_kwargs returns _LEAVE_BLOCK, the compiled counter does not move, and a compiled call reaches the eager wrapper and torch's varlen once with no dense SDPA call.
  • CUDA (probe True or False), ROCm with the probe passing, and ROCm fp32 rows keep (cu_seqlens, carrier) and count as compiled.

Both arms on CPU (-o addopts= -m "not server and not native_mxc"), each importing its own tree:

Arm New test file tests/test_hf_packed_attention.py + new file
main (merge base) 1 failed (_LEAVE_BLOCK expected, got the tuple), 4 passed 1 failed, 76 passed, 102 skipped
this branch 5 passed 77 passed, 102 skipped

Not proven here

…t run in the graph

When the in-graph probe refuses torch's flash varlen on ROCm (its fake kernel's logsumexp
rank differs, gfx1151 torch 2.11), _block_varlen_prepare still returned cu_seqlens, so the
traced call attended with SDPA over the dense mask inside the block and was counted as
compiled. Return _LEAVE_BLOCK there instead so the eager varlen wrapper runs. CUDA unchanged.

(cherry picked from commit a3aafcf6e8ec85998ecc9fdb1b25fbf4f5e4e576)
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T08:47:46.501128Z 84bbebd Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 84bbebda5b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 7d2829a into main Nov 19, 2026
@danielhanchen
danielhanchen deleted the kp-rocm-block-varlen branch November 19, 2026 10:09
oobabooga pushed a commit to oobabooga/unsloth that referenced this pull request Nov 20, 2026
…fallback for rejected varlen layers (unslothai#18635)

Follow-up fixes for unslothai#18435, unslothai#18494, found while re-checking the PRs
merged on 2026-11-19. One commit per fix; every fix has a test that
fails on main and passes here.

| Fix | Follows up | Severity |
|---|---|---|
| ROCm packed attention: rows eager varlen rejects stay dense in the
block | unslothai#18435 | P2 |
| Packed SFT: host lengths survive an in-place BatchEncoding.to() |
unslothai#18494 | P2 |

## Tests (this branch vs main `54af93780b`, CPU)

- New and changed tests: main 7 failed / 3 passed, this branch 10
passed. Each test loads the code of its own tree.
- Neighbouring suites on this branch: packed attention, host lengths and
padding-free eval suites: 130 passed, 103 skipped.
- `prepush_gate.py` passes.

## ROCm packed attention: rows eager varlen rejects stay dense in the
block (follows up unslothai#18435)

#### Summary

Follow-up to unslothai#18435. On ROCm builds where torch's flash varlen cannot
run inside a compiled graph, packed layers that the eager varlen wrapper
rejects anyway now stay inside the compiled block on the dense path.
Before this change they left the block, which costs a graph break per
layer, and then ran the same dense attention eagerly.

#### What broke

unslothai#18435 made `_block_varlen_prepare` return `_LEAVE_BLOCK` for every fp16
/ bf16 packed layer with head dim up to 256 whenever the in-graph varlen
probe refuses. The eager wrapper then checks the call with
`_static_window`, which rejects:

- attention sinks (gpt-oss) and logit softcapping (`_softcapped`);
- a head dim that is not a multiple of 8;
- non-causal attention;
- attention dropout in training.

For those layers the eager wrapper calls the original dense SDPA. So the
row left the compiled block only to run the attention it would have run
inside the graph before unslothai#18435.

#### Repro (CPU, ROCm faked through `torch.version.hip`, in-graph probe
refusing)

| layer | main | this branch |
|---|---|---|
| sinks, softcap, head_dim 20, `is_causal=False`, dropout 0.1 in
training | `_LEAVE_BLOCK` (graph break, then dense) | `None` (dense
inside the block) |
| eligible layer (also dropout 0.1 in eval, dropout 0.0 in training) |
`_LEAVE_BLOCK` (eager varlen) | `_LEAVE_BLOCK` (eager varlen) |

#### Fix

`_eager_varlen_rejects(attention, kwargs, head_dim)` mirrors the
layer-level conditions of `_static_window`, which need no tensors. When
it is true, the ROCm branch returns `None` and the layer keeps the
existing dense path. It does not count as `compiled`. Eligible layers,
CUDA builds and ROCm builds whose varlen traces are unchanged.

#### Tests

New `tests/test_hf_packed_attention_rocm_static_reject.py` (CPU).
Command (per worktree): `python -m pytest -o addopts= -m "not server and
not native_mxc" -p no:cacheprovider -q
tests/test_hf_packed_attention_rocm_static_reject.py
tests/test_hf_packed_attention_rocm_leave_block.py
tests/test_hf_packed_attention.py`. Each arm imports its own tree (the
test asserts it).

| arm | result |
|---|---|
| main (635532f) | 5 failed, 78 passed, 102 skipped |
| this branch | 83 passed, 102 skipped |

#### Not proven here

- No ROCm hardware run. Step time for packed gpt-oss on gfx1151 (main vs
this branch) needs the AMD CI.
- Per-call conditions such as an autocast dtype mismatch are still
decided in the eager wrapper.

## Packed SFT: host lengths survive an in-place BatchEncoding.to()
(follows up unslothai#18494)

#### What broke

unslothai#18494 wraps accelerate's `send_to_device` so that the CPU
`packed_seq_lengths` from the packing collators travels as a host tuple
on the moved tensor. That avoids a blocking `.tolist()` per packed
micro-batch. The carry read the CPU tensor after `send_to_device`
returned. A `BatchEncoding`, which transformers'
`DataCollatorForLanguageModeling` returns and which Unsloth installs in
place of `DataCollatorForSeq2Seq` (`unsloth/models/rl.py:3312`), moves
in place: `BatchEncoding.to()` replaces its tensors and returns `self`.
By the time the carry ran, the "before" batch already held the device
tensor, so it attached nothing. Every packed micro-batch then took the
device read again.

#### Repro (CPU, `meta` device, real accelerate `send_to_device`)

- main: `moved is batch`, and `_unsloth_lengths_tuple` is `None`
- this branch: `_unsloth_lengths_tuple == (3, 2, 4)`

#### Fix

The wrapper reads the host tuple from the CPU tensor before calling the
original `send_to_device`, then attaches it to the moved tensor when
that tensor is off the CPU and has the same length. Plain dict batches
behave as before.

#### Flip test

`tests/test_packed_host_lengths_batch_encoding.py`:

- main: 1 failed
- this branch: 1 passed
- `tests/test_packed_host_lengths_and_eval_flush.py` passes on both; it
is updated for the helper's new signature.

## Not proven here

ROCm hardware for the packed attention change; step time of packed SFT.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant