Skip to content

Fix GKD normalization after response generation - #15222

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
taking-lying-flat:fix/gkd-generated-token-normalization
Oct 26, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
taking-lying-flat:fix/gkd-generated-token-normalization

Conversation

@taking-lying-flat

Copy link
Copy Markdown
Contributor

GKD counts valid labels in get_batch_samples() before training_step() replaces the dataset responses with student-generated or teacher-generated responses. The distillation loss then receives num_items_in_batch from 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.

@danielhanchen

Copy link
Copy Markdown
Member

Two things on the latest Repo tests (CPU, rest) run:

  • From this PR: tests/test_formatter_fixed_point.py::test_every_tracked_python_file_is_already_formatted flags unsloth/models/rl_replacements.py. The repo's formatter (ruff with the kwargs-spacing hook) would still change the edited lines, so pre-commit.ci fails the next PR that touches the file. Running python scripts/run_ruff_format.py unsloth/models/rl_replacements.py and committing the result fixes it. Main's copy is already a fixed point.
  • From main, not this PR: test_float8_linear_trains_under_native_fsdp2 is fixed by Train the float8 FSDP2 reference in a fresh process like the sharded ranks #15250, and the Source lint duplicate import by Drop the duplicate has_real_cuda import in the torchao route test #15239. test_tp2_x_fsdp2_dp2_matches_one_process is an intermittent failure on main that is still being looked at.

Copy link
Copy Markdown
Contributor Author

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; test_every_tracked_python_file_is_already_formatted now passes locally. This commit only changes string delimiters—the AST and generated code are unchanged.

danielhanchen added a commit that referenced this pull request Oct 25, 2026
…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.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…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).
@danielhanchen danielhanchen self-assigned this Oct 26, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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 ⚠️ Failed 2026-10-26T05:54:25.193201Z
We couldn’t complete this review. Comment @codex review to try again.
8791a38 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

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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

@codex review

2 similar comments
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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

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 0 / 0 = NaN. Since this branch does not accept maintainer edits, the guard (clamp to at least 1) and a regression test are in #15328, which will be merged right after this one.

@danielhanchen
danielhanchen merged commit b39fc88 into unslothai:main Oct 26, 2026
31 of 37 checks passed
danielhanchen added a commit that referenced this pull request Oct 26, 2026
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]>
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.

2 participants