Skip to content

Remove hidden host-device syncs from per-step training paths - #15133

Merged
danielhanchen merged 6 commits into
mainfrom
dh/s6-hidden-syncs
Oct 24, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
dh/s6-hidden-syncs

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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:

site syncs / step why
accelerate send_to_device from the Trainer loop 4 (3 padded) pinned batch tensors copied with a blocking .to(device): one stream drain per tensor
get_packed_info_from_kwargs 1 lengths.max().item()
build_xformers_block_causal_mask (and the SDPA mask, packed_segment_lengths) 1 a second D2H read of the same lengths via .tolist()
cover_padded_cu_seqlens 1 cu_seqlens[-1].item() (plus torch.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 with torch.tensor(live, device=cuda) whenever a rank holds an empty shard, and _unsloth_average_gradients (DDP GRPO) built its present mask with torch.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 and cover_padded_cu_seqlens reuse it (only when the tensors are the ones that read produced; any other seq_info takes the old route). Lengths that arrive on the host are staged as one int32 buffer (lengths ++ cu_seqlens, same cumsum) and sent in one pinned non_blocking copy. The pad tail is cu_seqlens.new_full(...), a fill kernel.
  • unsloth/models/_utils.py + the inner loop in llama.py: _unsloth_non_blocking_batches turns on accelerate's dataloader_config.non_blocking when dataloader_pin_memory is on and the device is CUDA. The copy stays stream-ordered and the pinned block is held until it lands. UNSLOTH_NON_BLOCKING_BATCHES=0 opts 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 pinned non_blocking copy.

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_lengths and the SDPA mask equal the old device-derived values with torch.equal; a foreign seq_info still reads cu_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.
  • Same file, CUDA only (skipped without a GPU, run on a Kaggle T4: 9 passed): host lengths make 0 syncs per step through the packing helpers (and 1 for device lengths, the one read), native_clip_grad_norm_ with an empty shard makes 0.
  • Existing packing, attention-dispatch, varlen, FSDP2-native clip / units, GRPO DDP average and compile-reset suites: 272 passed, 10 skipped (CPU).
  • Audit, base vs head in one Kaggle T4x2 kernel (syncs per step, 5 steps after warmup):
case base head
SFT padding-free (default) 13 5
SFT packed 13 5
SFT padded 7 4
native FSDP2 LoRA, 2 ranks (per rank) 18 8
GRPO (HF generate, prefix grouper) 222.7 222.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), 1 GradScaler.get_scale() (fp16 only).

  • Numerics: the first step's loss is bitwise identical base vs head in every case. From the first backward on, the stack is not run-to-run deterministic even with 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.
  • Step time, SFT padding-free, base / head alternated ABBA on one card, 40 timed steps per run, CUDA events at step end:
    • T4 (fp16), two kernels, 8 runs each: head -2.45% and -2.28% (median of run medians). All four ABBA blocks favour head (-4.5%, -2.0%, -2.3%, -1.4%), but the base A/A spread is 3.3% / 5.4%, so the gain is about the size of the noise.
    • L4 (bf16, 11 -> 3 syncs per step), 12 runs: -0.74%, blocks +0.59%, -0.26%, +0.02%, A/A spread 3.2%. No measurable change.
    • So this is a sync-count and launch-queue hygiene change. At this size the step is not launch-bound enough for the removed syncs to show above noise. The gain should be larger when the host barely keeps ahead (small models, CPU-starved hosts).

Not covered

  • The transformers logging syncs and the fp16 GradScaler.get_scale() read in the fused CE (its backward needs the scale as a float).
  • GRPO's syncs are in HF generate, TRL's shuffle and the flex attention math fallback on sm75; untouched here.
  • _varlen_from_position_ids (hybrid models / TRL padding-free DPO without lengths) still syncs; it needs nonzero.
  • The FSDP2 empty-shard and DDP GRPO paths are covered by unit and CUDA tests only; the audit models never hit them.

- 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
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T15:54:59.316086Z 63ba3c0 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 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: 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".

Comment thread unsloth/models/rl.py Outdated
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 63ba3c006b

ℹ️ 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 50bb320 into main Oct 24, 2026
@danielhanchen
danielhanchen deleted the dh/s6-hidden-syncs branch October 24, 2026 15:56
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 25, 2026
…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>
danielhanchen added a commit that referenced this pull request Oct 28, 2026
## 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>
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