Skip to content

GRPO: take the per-step host syncs out of the loss path - #15855

Merged
danielhanchen merged 6 commits into
mainfrom
dh/s6-d1-grpo
Oct 28, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
dh/s6-d1-grpo

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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.

compute_loss read every logged metric with .item() (completion_length, kl,
the five clip ratios, and the vLLM IS metrics), and trl's nanmin / nanmax
add two more reads each, so the step stalled on the forward before it
could queue backward. The values now stay on device and are read in one
batched transfer when the trainer logs (flushed before log, bounded at
4096 pending); nanmin / nanmax use a sync-free equivalent. Appended floats
are identical to the old .item() values.

PrefixGrouper's build_group_layout read ids, completion starts, run starts,
run lengths and a contiguity flag separately: now one transfer, and the
largest left pad comes off the host copy.

get_packed_info_from_kwargs and _host_segment_lengths use host ints a
producer attached as _unsloth_lengths_tuple (unsloth-zoo GRPO packing
does) instead of reading the lengths back.

Tiny Qwen3 GRPO on an L4 (HF generate): steady-state training-phase syncs
31 -> 7 per step, total 173 -> 149; logged metrics and final weights
bitwise identical.
compute_loss now defers its metric reads to the next log call, so the
test logs before checking the train / eval buckets and loads the new
helpers with the rest of compute_loss.
@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-28T22:13:17.419627Z 5ac267c 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: 2a82043576

ℹ️ 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_replacements.py Outdated
Comment on lines +4853 to +4854
dtype = torch.float64 if is_float else torch.int64
host = torch.stack([pending[i][1].reshape(()).to(dtype) for i in idx]).tolist()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Avoid device-side float64 conversion on FP64-less XPUs

On Intel Arc XPUs without FP64 support, flushing any floating-point GRPO metric now attempts a device-side conversion to torch.float64, which raises instead of logging and stops training at the first log call (or the 4096-entry flush). This hardware limitation is already handled elsewhere in the repository, including unsloth/models/falcon_h1.py and device_has_fp64 in studio/backend/core/inference/video_minimax_h3_pdd.py; the previous .item() calls did not require FP64 device operations. Batch float16/bfloat16/float32 metrics in float32, or perform the float64 conversion after transferring to the CPU.

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 4d83935. The flush no longer converts anything to float64 on the device: float16 / bfloat16 / float32 metrics are stacked as float32 (which holds all three exactly, so each logged value still equals .item()), integers as int64, and only a metric that is already float64 keeps its own float64 group. The conversion to Python floats happens on the host via .tolist(). Added test_flush_never_converts_to_float64_on_device, which records every dtype requested through Tensor.to during the flush and checks float64 never appears and the values match .item() for float32, bfloat16, float16 and int64; it fails on the previous head.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 4d83935e3c

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 5ac267c8ec

ℹ️ 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 b80df64 into main Oct 28, 2026
@danielhanchen
danielhanchen deleted the dh/s6-d1-grpo branch October 28, 2026 22:53
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