Repository navigation
Packed SFT: read packed lengths on the host; loss-only eval skips the per-2-batch cache flush - #18494
Merged
Merged
Conversation
…: 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.
Member
Author
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Two small per-batch round trips on Unsloth's own paths:
packed_seq_lengthsin the batch as a CPU tensor. The Trainer's dataloader (acceleratesend_to_device) moves it to the GPU, andget_packed_info_from_kwargsthen took theelsebranch and didtuple(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 dataloadersend_to_deviceonce (installed when sample packing or padding-free metadata is enabled) and attaches the host tuple to the moved tensor. The existing_unsloth_lengths_tuplepath (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 movedpacked_seq_lengthstensor.eval_accumulation_stepsto 2 (or the GA count), so HF'sevaluation_loopcallstorch.cuda.empty_cache()every 2 eval batches. In loss-only eval (nocompute_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_loopis wrapped to run loss-only evals witheval_accumulation_steps = Noneand restore it after. Evals that keep logits (compute_metrics), inputs (include_for_metrics = ["inputs"]) or usebatch_eval_metricsare untouched.UNSLOTH_EVAL_EMPTY_CACHE=1keeps the old flush.Evidence
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 ametadevice through accelerate'ssend_to_device, so any device read raises; the eval test countstorch.cuda.empty_cachecalls through a realTrainer.evaluate(6 flushes for 12 batches before, 0 after, eval loss bitwise equal; 6 withcompute_metricsand with the opt-out).torch.cuda.set_sync_debug_modecensus over 16 micro-batches): synchronizing calls 33 before, 17 after. The 16packing.py get_packed_info_from_kwargssyncs 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):
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
keep.nonzero()in unsloth_zoofused_losses/fused_linear.py _keep_index), so the stream still drains once per micro-batch; that is a separate change.