Repository navigation
Remove hidden host-device syncs from per-step training paths - #15133
Conversation
- packing: one D2H read of the packed lengths per batch (was one per helper: max().item(), cu_seqlens[-1].item(), .tolist() in the xformers / SDPA mask builders); host lengths are staged once and sent in one pinned non_blocking copy; the padded cu_seqlens tail is a fill kernel, not torch.tensor(device=cuda) - trainer loop: pinned batches are copied with non_blocking=True (accelerate's default blocking copy drained the stream once per batch tensor per step); UNSLOTH_NON_BLOCKING_BATCHES=0 opts out - fsdp2_native clip: empty-shard norms are stacked, not scattered through a torch.tensor(live, device=cuda) index - DDP grad averaging: the present mask is a pinned non_blocking copy
|
@codex review |
Codex Review SummaryThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c1653bde35
ℹ️ 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".
| return | ||
| device = params[0].device | ||
| present = torch.tensor([p.grad is not None for p in params], dtype = torch.uint8, device = device) | ||
| present = torch.tensor([p.grad is not None for p in params], dtype = torch.uint8) |
There was a problem hiding this comment.
Explicitly allocate host staging tensors on CPU
When training under torch.set_default_device("cuda"), this factory creates present on CUDA rather than CPU, so the following present.pin_memory() raises instead of averaging gradients. The previous implementation explicitly selected the parameter device and worked in this context. Specify device="cpu" for the host allocation; the new staged = torch.zeros(...) allocation in _stage_packed_metadata needs the same treatment, since its CPU cumsum input and subsequent pinning also require a CPU buffer.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in 518820e. Both host buffers (present in _unsloth_average_gradients and staged in _stage_packed_metadata) now pass device = "cpu", so a torch.set_default_device("cuda") context no longer moves them before pin_memory(). Added test_stage_packed_metadata_stays_on_host_under_a_default_device, which fails on the previous commit and passes now.
|
@codex review |
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
…to pageable copies (unslothai#15199) ## Problem unslothai#15133 removed a host sync from `get_packed_info_from_kwargs` by reading the packed lengths back once as a host tuple (`tuple(lengths.tolist())`) and staging host lengths through one pinned `non_blocking` copy. Two side effects: 1. Under a user `torch.compile(..., dynamic = True)` the host tuple specializes the graph on the number of segments, so every new segment count is a recompile. CPU repro over 12 segment counts (3 to 14): 4 graphs before unslothai#15133, 12 after, and the recompile limit is hit. 2. `staged.pin_memory()` runs inside the traced region on a cold compile and cannot be traced (`aten._pin_memory` is not implemented for the tracing tensors). Pinning also had no fallback when host memory cannot be pinned (pinned memory limit, WSL), here and in the DDP present mask in `rl.py`. ## Change - `unsloth/utils/packing.py`: when `torch.compiler.is_compiling()`, `get_packed_info_from_kwargs` takes the pre-unslothai#15133 tensor path (device lengths, device cumsum, `lengths.max().item()`), with no `pin_memory` and no host tuple. The downstream mask helpers then find no cached host lengths and take their existing route. The eager path is unchanged, so the sync removal from unslothai#15133 stays. - `_pinned_to_device`: pinned `non_blocking` copy, or a plain pageable copy when `pin_memory()` raises. - `unsloth/models/rl.py` `_unsloth_average_gradients`: the same fallback for the DDP present mask. ## Tests `tests/utils/test_packing_host_sync.py` (CPU): - compile with `dynamic = True` over 12 segment counts traces at most 4 graphs and returns the right values; - while compiling, the returned lengths / cu_seqlens / max equal the old device-derived values and no host tuple is cached; - `_pinned_to_device` returns the same tensor when `pin_memory` raises. | | before (main) | after | |---|---|---| | test_packing_host_sync.py | 3 failed, 8 passed, 2 skipped (CUDA only) | 11 passed, 2 skipped | | packing, attention mask, hybrid packing, GRPO DDP average suites | | 195 passed, 7 skipped | GPU (Colab T4, torch 2.11.0+cu130). Each case ran in a fresh process so the compile cache starts cold, with the same probe on the `packing.py` from main and from this branch: | case | main | this branch | |---|---|---| | cold `torch.compile` (default), 12 segment counts, fwd + bwd | fails: `NYI: aten._pin_memory.default` | passes, 4 graphs | | cold `torch.compile(dynamic = True)`, same | fails: `NYI: aten._pin_memory.default` | passes, 3 graphs | | eager, `pin_memory` raising | `RuntimeError` | passes, same cu_seqlens / max | | eager, host lengths, syncs under `set_sync_debug_mode("warn")` | 0 | 0 | The last row shows the eager path from unslothai#15133 still makes no sync. ## Not covered - The `rl.py` DDP fallback has no test of its own (it needs CUDA params plus a process group). It is the same three-line try / except as `_pinned_to_device`. - A real pinned memory limit (as opposed to a `pin_memory` that raises) was not reproduced. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
## Summary GRPO training steps still paid about 30 host syncs per step outside generation after the SFT work in #15133. Most of them sat in `compute_loss` right before backward, so the CPU waited for the forward to finish before it could queue backward. - `compute_loss`: every logged metric (`completion_length`, `kl`, five clip ratios, the vLLM importance sampling metrics) was read with `.item()`, and TRL's `nanmin` / `nanmax` add two more reads each. The values now stay on device and are read in one batched transfer when the trainer logs. The flush runs before `log`, and the queue is bounded at 4096 entries for runs that log rarely. `nanmin` / `nanmax` use a sync-free equivalent: NaN becomes +inf / -inf, and an all-NaN input still returns NaN. - `prefix_grouper.build_group_layout`: ids, completion starts, run starts, run lengths and the contiguity flag were five separate reads. They are now one transfer, and the largest left pad comes from that host copy. - `packing.get_packed_info_from_kwargs` / `_host_segment_lengths`: when a producer builds `packed_seq_lengths` from host ints and attaches them as `_unsloth_lengths_tuple`, the lengths are not read back. unsloth-zoo's GRPO packing does this in the companion zoo PR. With an older zoo the attribute is absent and the old read runs. Appended metric values are the same floats `.item()` returned: float64 holds every float32 / bfloat16 / float16 value exactly. TRL's metric dict, its `log`, and the logged keys are unchanged. Works with TRL 0.22.2 through 1.15. ## Measurements Colab L4, torch 2.14.1, tiny Qwen3 (`trl-internal-testing/tiny-Qwen3ForCausalLM`), LoRA r8, HF generate (no vLLM), bs 8, 4 generations, 32 completion tokens. Syncs were counted with `torch.cuda.set_sync_debug_mode("warn")` and attributed to file and line. | run | base syncs per step | head syncs per step | |---|---|---| | max_steps 3 (steps 1 / 2 / 3) | 255 / 222 / 173 | 230 / 198 / 149 | | steady state, outside generation (loss + backward + log) | 31 | 7 | | beta 0.04, num_iterations 2, training-only steps | 30 | 6 | | TRL 0.22.2 + transformers 4.57.6, steady state | 195 | 171 | What remains per steady step outside generation: one zoo packed-lengths read, one PrefixGrouper layout read, `max_left_pad`, the fused logprob `_keep_index`, the batched metric read, and transformers' two logging reads. Generation (about 102 syncs per step: decode stop check, SDPA mask check, decode graph bound) and TRL's reward scoring (about 40) are host-driven and not touched here. Numerics: every logged metric (26 keys per step) and a sha256 of the trained LoRA weights are bitwise identical between base and head. This holds for the 3-step and 6-step audits, the beta / num_iterations run (nonzero KL), the TRL 0.22.2 stack, and all eight 33-step timing runs. Step time (8 runs, ABBA order, 30 timed steps each): base run medians 134.4 / 133.8 / 136.2 / 135.5 ms, head 135.8 / 136.5 / 135.1 / 133.5 ms. Head vs base is +0.37%, inside the 1.8% base A/A spread, so there is no measurable change at this size. The tiny model's step is dominated by generation. The removed syncs sat between forward and backward, so a launch-bound model (small, many layers) is where they should show. ## Tests `tests/utils/test_grpo_host_syncs.py` (CPU): - `nanmin` / `nanmax` match TRL's for float32 / bfloat16 / float16, including NaN, all-NaN and inf. - Deferred metrics: no `Tensor.item` / `Tensor.tolist` call during the step, one batched read at `log`, values and types equal to `.item()`, order kept, bounded flush. - The generated `compute_loss` source has no `.item()`. - `build_group_layout` makes exactly one device read and feeds `_build_groups` the same inputs as before over 200 random batches, including non-contiguous rows. - Attached host lengths skip the read, and a mismatched tuple is ignored. All 9 fail on main and pass here. `tests/test_grpo_metrics_bucket.py` now calls `log` before it reads the metric buckets, because the values land there at log time. It passes on main and here. The related CPU suites (153 files: GRPO, packing, prefix grouper, RL replacements) have the same 45 failures and 4 errors as main and nothing new. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Problem
Every SFT step paid several hidden host-device syncs that do not change any value. Each one drains the launch queue, so the GPU idles while Python rebuilds its lead. With
torch.cuda.set_sync_debug_mode("warn")over 5 steps after warmup (Qwen3-0.6B LoRA, T4, transformers 5.17.0, TRL 1.15.0, torch 2.14.1), the default padding-free SFT path hit 13 syncs per step. The Unsloth-owned ones in this repo:send_to_devicefrom the Trainer loop.to(device): one stream drain per tensorget_packed_info_from_kwargslengths.max().item()build_xformers_block_causal_mask(and the SDPA mask,packed_segment_lengths).tolist()cover_padded_cu_seqlenscu_seqlens[-1].item()(plustorch.tensor([total], device=cuda)when a pad tail exists)Two more sites are the same class but were not hit by the audit models:
native_clip_grad_norm_indexed withtorch.tensor(live, device=cuda)whenever a rank holds an empty shard, and_unsloth_average_gradients(DDP GRPO) built its present mask withtorch.tensor(..., device=cuda).Change
unsloth/utils/packing.py: the packed lengths are read back once per batch (lengths.tolist()); the max, the total and the host segment lengths come from that read, and the mask builders andcover_padded_cu_seqlensreuse it (only when the tensors are the ones that read produced; any otherseq_infotakes the old route). Lengths that arrive on the host are staged as one int32 buffer (lengths ++ cu_seqlens, same cumsum) and sent in one pinnednon_blockingcopy. The pad tail iscu_seqlens.new_full(...), a fill kernel.unsloth/models/_utils.py+ the inner loop inllama.py:_unsloth_non_blocking_batchesturns on accelerate'sdataloader_config.non_blockingwhendataloader_pin_memoryis on and the device is CUDA. The copy stays stream-ordered and the pinned block is held until it lands.UNSLOTH_NON_BLOCKING_BATCHES=0opts out.unsloth/models/fsdp2_native.py: empty-shard norms are interleaved with one shared identity scalar and stacked, instead of scattered through a device index tensor.unsloth/models/rl.py: the DDP present mask is a pinnednon_blockingcopy.The companion unsloth-zoo change (unslothai/unsloth-zoo#2061) removes the batch count and fused CE syncs (another 2 to 5 per step).
Tests
tests/utils/test_packing_host_sync.py(CPU): for 200 random packed batches (int32 / int64, 1 to 32 segments, pad tails 0 / 1 / 7 / 64) the staged buffer, lengths, cu_seqlens, max,cover_padded_cu_seqlens,packed_segment_lengthsand the SDPA mask equal the old device-derived values withtorch.equal; a foreignseq_infostill readscu_seqlens[-1];native_clip_grad_norm_with empty shards equals the old scatter implementation bitwise for p = 2, 1, inf, -inf, 3 and fp32 / fp16 / bf16; the non-blocking switch only fires for pinned CUDA loaders and honours the opt-out.native_clip_grad_norm_with an empty shard makes 0.Numbers include the zoo change. What remains per SFT step: 3 in transformers' own logging (
logging_steps=1), 1 packed lengths read (flash / xformers need the max on the host), 1GradScaler.get_scale()(fp16 only).use_deterministic_algorithms(base vs base differs at the 5th significant digit of the step-1 grad norm), and base vs head stays inside that A/A spread.Not covered
GradScaler.get_scale()read in the fused CE (its backward needs the scale as a float)._varlen_from_position_ids(hybrid models / TRL padding-free DPO without lengths) still syncs; it needsnonzero.