Skip to content

Packed SFT: read packed lengths on the host; loss-only eval skips the per-2-batch cache flush - #18494

Merged
danielhanchen merged 2 commits into
mainfrom
ss4s3-packed-sync
Nov 19, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
ss4s3-packed-sync

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Two small per-batch round trips on Unsloth's own paths:

  1. Packed / padding-free SFT: no device read of the document lengths. The packing collators put packed_seq_lengths in the batch as a CPU tensor. The Trainer's dataloader (accelerate send_to_device) moves it to the GPU, and get_packed_info_from_kwargs then took the else branch and did tuple(lengths.tolist()) (unsloth/utils/packing.py), a blocking device read at the start of every packed micro-batch. A tensor attribute does not survive .to(device), so this PR wraps accelerate's dataloader send_to_device once (installed when sample packing or padding-free metadata is enabled) and attaches the host tuple to the moved tensor. The existing _unsloth_lengths_tuple path (already used by the zoo GRPO producer) then reads the lengths without touching the device. Values are unchanged; only an attribute is added to the moved packed_seq_lengths tensor.
  2. Loss-only eval: no allocator flush every 2 batches. Unsloth defaults eval_accumulation_steps to 2 (or the GA count), so HF's evaluation_loop calls torch.cuda.empty_cache() every 2 eval batches. In loss-only eval (no compute_metrics, the default) nothing but the scalar losses is kept, so the flush only hands cached blocks back to the driver for the next batch to allocate again. Trainer.evaluation_loop is wrapped to run loss-only evals with eval_accumulation_steps = None and restore it after. Evals that keep logits (compute_metrics), inputs (include_for_metrics = ["inputs"]) or use batch_eval_metrics are untouched. UNSLOTH_EVAL_EMPTY_CACHE=1 keeps the old flush.

Evidence

  • CPU flip test tests/test_packed_host_lengths_and_eval_flush.py: 3 failed on the merge base, 3 passed here. The packed test moves a real TRL padding-free batch to a meta device through accelerate's send_to_device, so any device read raises; the eval test counts torch.cuda.empty_cache calls through a real Trainer.evaluate (6 flushes for 12 batches before, 0 after, eval loss bitwise equal; 6 with compute_metrics and with the opt-out).
  • Related suites (padding-free eval, packing caches, GRPO eval accumulation, eval return-logits restore, full-eval state) pass unchanged.
  • Correctness on B200 (tiny Qwen3 LoRA, packed SFT, GA 4, torch.cuda.set_sync_debug_mode census over 16 micro-batches): synchronizing calls 33 before, 17 after. The 16 packing.py get_packed_info_from_kwargs syncs are gone; the host lengths are used on every micro-batch (24 of 24 hits including warm-up, 0 device reads). Eval: 4 flushes before, 0 after, identical eval loss.

Speed (Colab L4, Qwen3-0.6B bf16 LoRA r 16, packed SFT, batch 2, GA 4, max length 1024)

Base = merge base, head = this branch, same VM, arms interleaved, 4 runs each (spread = min to max over the 4 base runs):

base median (range) head median (range) change
30 training steps (120 packed micro-batches) 29.93 s (29.69 to 30.06) 28.61 s (28.50 to 28.72) -4.4%
Loss-only eval, 192 batches (2nd eval) 3.763 s (3.743 to 3.796) 3.207 s (3.195 to 3.258) -14.8%

The training delta is the packing change alone (both arms flush the same 9 times during training); the eval delta combines both changes (eval batches are packed too). Eval loss matches across arms to the run-to-run noise of training (11.4043 to 11.4046 on both sides).

Notes

  • One other per-micro-batch sync remains on this path, inside the fused CE (keep.nonzero() in unsloth_zoo fused_losses/fused_linear.py _keep_index), so the stream still drains once per micro-batch; that is a separate change.
  • Training code path touched (packing metadata): worth one AMD gfx1151 packed SFT smoke run before merge.

…: skip the per-2-batch allocator flush

The Trainer's dataloader moves the collator's CPU packed_seq_lengths to the GPU, and
get_packed_info_from_kwargs then read it back with a blocking .tolist() at the start of every
packed micro-batch. Wrap accelerate's dataloader send_to_device once (when packing or
padding-free metadata is enabled) to attach the host tuple to the moved tensor; the existing
_unsloth_lengths_tuple path then reads it with no device round trip. Values are unchanged.

Unsloth defaults eval_accumulation_steps to 2 (or the GA count), so HF's evaluation_loop calls
torch.cuda.empty_cache() every 2 eval batches. In loss-only eval nothing is kept on the GPU, so the
flush only hands cached blocks back for the next batch to allocate again. Skip it for loss-only
eval (no compute_metrics, no inputs kept, no batch_eval_metrics); UNSLOTH_EVAL_EMPTY_CACHE=1 keeps
the old behaviour.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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-19T15:49:52.529528Z e218a34 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e218a3460d

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

[skip ci]
@danielhanchen
danielhanchen merged commit 7e4c8c4 into main Nov 19, 2026
@danielhanchen
danielhanchen deleted the ss4s3-packed-sync branch November 19, 2026 17:25
danielhanchen added a commit that referenced this pull request Nov 19, 2026
…der (#18525)

## Summary

`Repo tests (CPU, rest)` fails intermittently (seen on #18519, which
only touches Studio diffusion training):

```
FAILED tests/test_packed_host_lengths_and_eval_flush.py::test_carry_leaves_other_moves_alone
tests/test_packed_host_lengths_and_eval_flush.py:65: in test_carry_leaves_other_moves_alone
    assert accelerate_data_loader.send_to_device._unsloth_host_lengths_carry
E   AttributeError: 'function' object has no attribute '_unsloth_host_lengths_carry'
```

Reproduced on `main` by running that test on its own: `1 failed`.

## Root cause

#18494 added the test. It asserts that
`accelerate.data_loader.send_to_device` carries Unsloth's host-lengths
wrapper, but nothing in the test installs it: the wrapper is installed
by `packing.enable_padding_free_metadata()`, which only the test above
it calls. Under xdist the two tests can land on different workers, or
run in the other order, and then the assertion reads the stock
`send_to_device`. The product code is fine; the test depended on its
neighbour.

## Changes

- The test calls `packing._install_host_lengths_carry()` first. It is
idempotent (it returns early when the wrapper is already in place), so
the test now states its own precondition and keeps checking the same
three things: no tuple on an unrelated move, none on a plain batch, and
the wrapper marker.

## Testing

- `test_carry_leaves_other_moves_alone` alone: passes (fails on `main`).
- The whole file, in order and under `-n 3`: 3 passed.
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.
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