Repository navigation
Fix GKD normalization after response generation - #15222
danielhanchen merged 2 commits into
Conversation
|
Two things on the latest
|
|
Thanks @danielhanchen for tracking this down and separating the PR-specific formatting failure from the issues on main. Fixed in 8791a38 using the pinned formatter; |
…d copy (#15264) `tests/test_tp_native_gloo.py::test_tp2_x_fsdp2_dp2_matches_one_process[llama-True-lora_kwargs4]` fails now and then in `Repo tests (CPU, rest)` on unrelated PRs (#15159, #15174, #15217, #15218, #15222, #15225) with only `AssertionError: base_model.model.lm_head.weight`. Gradients, losses and norms all match in those runs. Only the saved `lm_head` copy differs. ## Cause The test, not the product. That case trains a full `lm_head` copy (`modules_to_save`, 512000 entries) with AdamW at lr 1e-2 and the default eps of 1e-8. At g = 0, Adam's `g / (sqrt(v) + eps)` has slope lr / eps = 1e6. Measured on main on this host: | | value | | --- | --- | | median step-0 lm_head grad | 5.7e-6 | | entries with step-0 grad below 1e-8 | 313 | | step-0 grad of the 10 worst saved-weight entries | 4e-11 to 7e-9 | | worst saved-weight diff / tolerance | 0.46 | So reduction-order noise of about 1e-12 on a near-zero gradient becomes about 5e-6 of weight. That is already half the `atol = 1e-5` here. A runner whose CPU kernels sum in a different order goes over it. ## Fix - Both arms use `AdamW(eps = 1e-6)`. The optimizer is still identical on both sides, and 1e-6 is small next to the typical gradient, so the head still trains. The worst entry drops to 0.0075 of the tolerance (60x headroom). - The saved-weight assert now keeps `assert_close`'s mismatch detail. It used to print only the key, which is why the CI logs never showed how far off the weight was. ## Verification - `tests/test_tp_native_gloo.py`: 38 passed. - Sabotage on the last step, after the norms are taken, so only the saved weight can catch it: - TP arm skips the lm_head update: fails, 511627 / 512000 mismatched, max abs diff 1.0e-2. - Each dp half's lm_head gradient scaled by +/-15% (a stand-in for a missing dp reduction): fails, 493693 / 512000 mismatched, max abs diff 8.1e-4. - No sabotage: passes.
…15273) `tests/test_pp_fsdp2_gloo.py::test_pp2_x_tp2_matches_one_process[gemma3]` fails now and then in `Repo tests (CPU, rest)`, for example on #15222, which does not touch parallelism. The failure is only `AssertionError: base_model.model.model.layers.0.self_attn.v_proj.lora_A.default.weight` from the step-0 grads check. ## Cause The tolerance, not the product. The step-0 grads check allows 2e-5 of each tensor's largest entry per element for every architecture. Measured on main on this host, gemma3's (pp 2, tp 2) grads differ from the one-process reference by: | | value | | --- | --- | | relative L2, every LoRA weight in layers 0 to 4 | 3e-6 to 2e-5 | | largest per-element diff / tensor max | 2.1e-5 | | worst entry vs the current bound | 0.999 | The error is uniform across layers and tensors, the shape of fp32 reordering rather than a wrong slice or a missing reduction. Gemma3 already has its own looser step-0 norm bound in this file (`STEP0_NORM_REL["gemma3"] = 3e-4`, against 1e-5 for llama and qwen3) for the same reason. The grads check had no per-architecture bound. ## Fix - `GRAD_ATOL_REL` gives gemma3 1e-4 and keeps llama and qwen3 at 2e-5. The two per-architecture tests pass it to `_check`. - The 5e-5 relative L2 bound over all grads is unchanged, so a systematic error still fails. - The per-tensor assert keeps `assert_close`'s mismatch detail. It used to print only the name. ## Verification - `tests/test_pp_fsdp2_gloo.py`: 12 passed. - Faults injected into the gemma3 step-0 grads of `layers.0.self_attn.v_proj.lora_A`, on both (pp 2, tp 2) and (pp 2, dp 2). Each fails the new gemma3 bound, and the clean results pass: - one entry off by 5e-4 of the tensor max; - the whole tensor with 1e-3 relative noise; - the tensor halved (a missing reduction).
|
@codex review |
1 similar comment
|
@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. |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ 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". |
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ 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". |
|
Thanks for this, the recount is right: on TRL 1.16 / transformers 5.20 the count passed to the loss went from 208 (dataset answers) to 24 (the generated tokens the loss actually sums), and the loss no longer moves when only the discarded answer changes. Off-policy and TRL 0.25 runs are bit-identical to main. One edge case: on TRL 1.7 and 1.8, a pad == eos tokenizer with every completion in the window an immediate EOS gives a recount of 0, and the JSD becomes |
Follow-up to #15222, which recounts GKD's `num_items_in_batch` from the generated labels. Merge it after #15222; until then this branch also carries #15222's two commits. On TRL 1.7 and 1.8, `generate_on_policy_outputs` masks every token equal to `pad_token_id`, EOS included when the tokenizer pads with EOS. A gradient accumulation window whose completions are all an immediate EOS therefore has zero supervised tokens, the recount returns 0, and TRL's `generalized_jsd_loss` returns `jsd.sum() / 0 = NaN` (the dataset count used before #15222 was nonzero, so the loss was 0). Unsloth's chunked JSD divides the same way. This clamps the shared count to at least 1 (tensor or int). The window's JSD sum is 0 in that case, so the loss becomes 0 instead of NaN; any window with supervised tokens is unchanged. It also adds `tests/python/test_gkd_generated_token_count.py`, which rewrites both TRL `training_step` layouts and the installed TRL's own source and checks: - `num_items_in_batch` equals the generated label count for on-policy and seq_kd, whatever the dataset answers were, including a short final window. - each microbatch is generated once and no internal key reaches the loss. - a mixed window (`lmbda=0.5`) draws the same random numbers as stock TRL. - off-policy keeps the dataset count; an unrecognised `training_step` is left alone. - an all-masked window counts 1, for int and tensor counts (fails without the clamp). | TRL 1.8 `generalized_jsd_loss`, all labels masked | loss | |---|---| | `num_items_in_batch = 0` (#15222 alone) | `nan` | | `num_items_in_batch = 1` (this PR) | `0.0` | | `num_items_in_batch = 4` (before #15222) | `0.0` | --------- Co-authored-by: taking-lying-flat <[email protected]>
GKD counts valid labels in
get_batch_samples()beforetraining_step()replaces the dataset responses with student-generated or teacher-generated responses. The distillation loss then receivesnum_items_in_batchfrom the original answers. As a result, changing an answer that is discarded can change the gradient scale even when the prompt and generated response are identical. This affects the normal on-policy path and sequence knowledge distillation.Prepare the replacement responses for the entire gradient accumulation window at the first
training_step(), then ask the parent trainer to recount valid tokens from the updated labels. Each microbatch receives that shared count, so unequal completion lengths retain their token weighting across the window. This also handles windows containing both generated and original responses, and a final window with fewer microbatches. Normalizing each microbatch independently would change these weights.The patch reuses TRL's existing generation code, including student/teacher selection and model unwrapping, and keeps generation after checkpoint RNG restoration. Each microbatch is generated once, and its internal count is removed before the loss receives the inputs. Fully off-policy training keeps the existing path.