Repository navigation
GRPO: take the per-step host syncs out of the loss path - #15855
Conversation
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.
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. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| dtype = torch.float64 if is_float else torch.int64 | ||
| host = torch.stack([pending[i][1].reshape(()).to(dtype) for i in idx]).tolist() |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…loat64 op on FP64-less XPUs
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! 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". |
…del trainer frees it at once [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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]
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_lossright 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'snanmin/nanmaxadd two more reads each. The values now stay on device and are read in one batched transfer when the trainer logs. The flush runs beforelog, and the queue is bounded at 4096 entries for runs that log rarely.nanmin/nanmaxuse 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 buildspacked_seq_lengthsfrom 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, itslog, 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 withtorch.cuda.set_sync_debug_mode("warn")and attributed to file and line.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/nanmaxmatch TRL's for float32 / bfloat16 / float16, including NaN, all-NaN and inf.Tensor.item/Tensor.tolistcall during the step, one batched read atlog, values and types equal to.item(), order kept, bounded flush.compute_losssource has no.item().build_group_layoutmakes exactly one device read and feeds_build_groupsthe same inputs as before over 200 random batches, including non-contiguous rows.All 9 fail on main and pass here.
tests/test_grpo_metrics_bucket.pynow callslogbefore 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.