Skip to content

Packed attention lengths: keep them across BatchEncoding.to(), dense fallback for rejected varlen layers - #18635

Merged
danielhanchen merged 3 commits into
mainfrom
kr4-packed-attention-lengths
Nov 20, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
kr4-packed-attention-lengths

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Follow-up fixes for #18435, #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 #18435 P2
Packed SFT: host lengths survive an in-place BatchEncoding.to() #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 #18435)

Summary

Follow-up to #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

#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 #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 #18494)

What broke

#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.

…mpiled block

When ROCm varlen cannot run in the graph, _block_varlen_prepare sent every fp16 / bf16 packed layer to
the eager wrapper (_LEAVE_BLOCK). Layers that the wrapper's _static_window rejects anyway (attention
sinks such as gpt-oss, logit softcapping, head_dim not a multiple of 8, non-causal, attention dropout
in training) then ran the same dense SDPA eagerly after a graph break. Those layers now keep the dense
path inside the block, as before #18435; eligible layers still leave for eager varlen.
… batches keep them

BatchEncoding.to() moves its tensors in place and returns self, so the send_to_device carry
read the already-moved tensor and attached nothing; every packed micro-batch went back to a
blocking .tolist(). Read the CPU lengths before calling send_to_device.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 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-20T14:34:11.772916Z aa4d9c2 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e87e530b57

ℹ️ 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".

Comment thread unsloth/utils/hf_packed_attention.py Resolved
@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: aa4d9c257a

ℹ️ 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 434d8f5 into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the kr4-packed-attention-lengths branch November 20, 2026 16:19
FiditeNemini pushed a commit to FiditeNemini/unsloth that referenced this pull request Nov 24, 2026
…hs (unslothai#18720)

unslothai#18494 and unslothai#18635 carry the packed document lengths to the device as a
host tuple, so a packed micro-batch no longer reads them back.
`UNSLOTH_TOKEN_BUDGET` undoes that for the batches it splits: the split
calls `.tolist()` on the device tensor, and each chunk gets a new device
tensor with no tuple, so every chunk's forward reads its lengths from
the device again.

The split now uses the attached tuple when it matches the tensor and
attaches each chunk's own lengths. Values are unchanged. With labels in
the batch the split still makes its one read of the labels at the cut
points.

`tests/test_token_budget_host_lengths.py` splits a packed batch on the
`meta` device, where any device read raises, and passes the chunks to
`get_packed_info_from_kwargs`: 3 failed on main fe5340f, 3 passed
here. The token budget and host-length suites give 93 passed, 1 skipped
with and without the change. Step time was not measured.


## Takeover update
Checked the chunk lengths against the packing host-lengths contract (a
tuple with the matching count, as attached by _carry_host_lengths). On
an L4 (function-level probe), the per-chunk forward length reads that
synced went from 5 to 0 for a 5-chunk split, and the split itself drops
one lengths read (6 -> 5 syncs without labels, 8 -> 7 with labels; the
rest is the labels boundary check, which exactness needs). The second
test now imports unsloth.utils.packing directly instead of skipping on
ImportError. Applies cleanly on current main and is independent of
unslothai#18963 (198 token budget + packing tests pass on the combined tree).

---------

Co-authored-by: danielhanchen <[email protected]>
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