Skip to content

GRPO under DeepSpeed ZeRO-3: score with the gathered head, no_grad instead of inference_mode - #14395

Merged
danielhanchen merged 5 commits into
mainfrom
dh/s2-w2-grpo
Oct 20, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
dh/s2-w2-grpo

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

  • Score old / reference logprobs with the gathered ZeRO-3 head (unsloth_zoo helper from unslothai/unsloth-zoo1900, guarded import so older zoo keeps today's behaviour).
  • On a DeepSpeed launch, score under no_grad instead of inference_mode, as FSDP already does: ZeRO-3 keeps parameters gathered there, and the next training step failed with Inference tensors cannot be saved for backward.

Tests

Not covered

  • Parity with one GPU, vLLM generation, a trainable head.

… mode

ZeRO-3 releases the output head after the model forward, so the old / reference logprob
scoring read a 0-element placeholder (lm_head.shape[1] IndexError). Gather it once per call
through unsloth_zoo's read-only helper when present. The scoring forwards also ran under
torch.inference_mode, and ZeRO-3 keeps the parameters it gathers there (persistent ones for
good), so the training step failed with 'Inference tensors cannot be saved for backward';
score under no_grad on a DeepSpeed launch, as FSDP already does.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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-20T22:52:27.485942Z 745350a Manual request
🔒 Security Review ⚠️ Failed 2026-10-20T18:50:09.407498Z
We couldn’t complete this review. Comment @codex security review to try again.
4582e54 PR opened
ℹ️ 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

@danielhanchen danielhanchen self-assigned this Oct 20, 2026

@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: 4582e54fb2

ℹ️ 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 +2629 to +2630
except ImportError:
pass

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 Require the Zoo version that supplies the gather helpers

When an installation retains the currently allowed unsloth_zoo==2026.10.7, these symbols do not exist, so this ImportError is silently swallowed and ZeRO-3 continues with the partitioned, zero-element lm_head; the subsequent lm_head.shape[1] access or projection therefore still fails. Raise the dependency floor to the first Zoo release containing these helpers, or provide an in-repo fallback, so ordinary upgrades actually receive the advertised ZeRO-3 fix.

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.

Not changing this here. The unsloth_zoo floor in pyproject.toml is only moved by the release commits ("Versioning"), which ship unsloth and unsloth_zoo together; a PR that bumps it to an unreleased zoo version would make main uninstallable until that release exists. The zoo side is unslothai/unsloth-zoo#1900, merged before this one, and the next release raises the floor to the zoo release carrying it. The guarded import only keeps a mixed older zoo on today's behaviour.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 42336b7b43

ℹ️ 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: 745350a6d0

ℹ️ 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 added a commit that referenced this pull request Oct 20, 2026
## Problem


`tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding`
fails on main, so the `Repo tests (CPU, rest)` shard is red on every PR
(for example #14395):

```
AssertionError: 3 file reads in the test trees touch a checked-in file with the platform default encoding, so they break on Windows as soon as that file gains a non-ASCII byte. Pass encoding = "utf-8": ['tests/test_grouped_gemm_mixed_tma_device.py:218: read_text()', ...]
AssertionError: 2 file reads in the test trees touch a checked-in file with the platform default encoding, ... ['studio/backend/tests/test_diffusion_vae_oom.py:1726: read_text()', 'tests/test_legacy_block_compile_install.py:15: read_text()']
```

Three test files that merged today read checked-in sources with a bare
`read_text()`:

| File | Reads | Added by |
|---|---|---|
| `tests/test_grouped_gemm_mixed_tma_device.py` | 3 | #14358 |
| `studio/backend/tests/test_diffusion_vae_oom.py` | 1 | #13802 |
| `tests/test_legacy_block_compile_install.py` | 1 | #14398 |

The guard is right: on Windows, `read_text()` decodes with the locale
codec (cp1252), so these break as soon as one of those sources gains a
non-ASCII byte.

## Fix

Pass `encoding = "utf-8"` to the five reads. No other change.

## Verification

- On main: `tests/test_source_read_encoding.py`: 2 failed, 14 passed
(the two failures above).
- With this change: the guard and the two touched `tests/` files pass,
apart from 4 `test_legacy_gate` errors.
- Some failures on this host are the same with and without this change,
so they come from the local environment, not this PR:
- the 4 `test_legacy_gate` setup errors in
`tests/test_legacy_block_compile_install.py`;
- 8 failures in `studio/backend/tests/test_diffusion_vae_oom.py` (102
passed).
@danielhanchen
danielhanchen merged commit b824412 into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the dh/s2-w2-grpo branch October 20, 2026 23:49
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 25, 2026
…eds no_grad (unslothai#14673)

## Summary
unslothai#14395 switched generation and logprob scoring from
`torch.inference_mode()` to `torch.no_grad()` on any DeepSpeed launch
(`ACCELERATE_USE_DEEPSPEED` or a DEEPSPEED accelerator state). The
failure it fixed, "Inference tensors cannot be saved for backward",
comes from ZeRO-3 keeping gathered persistent parameters. ZeRO-1 and
ZeRO-2 never partition parameters, so they lost inference mode for no
reason (a small decode overhead; TRL itself generates under `no_grad`,
so results are the same either way).

`_get_inference_mode_context_manager` now asks for the ZeRO stage before
falling back to `no_grad`:
- transformers' `is_deepspeed_zero3_enabled()` (the Trainer's DeepSpeed
config) returning True means stage 3;
- the accelerator's DeepSpeed plugin: the stage in its DeepSpeed config,
else its `zero_stage` field;
- `ACCELERATE_DEEPSPEED_ZERO_STAGE` from `accelerate launch`.

Any source saying 3, or no source at all, keeps `no_grad` exactly as
today. A known stage below 3 keeps `inference_mode`. The `ds_id` check
on partitioned parameters is unchanged and still wins.

## Tests
`tests/test_fsdp_generation_grad_mode.py`:
- stage 0/1/2 from the launcher env keep inference mode, stage 3 gets
no_grad;
- the plugin's config stage wins over its field; a config without a
stage falls back to the field;
- a ZeRO-2 launch env with a ZeRO-3 Trainer config still gets no_grad;
- a ZeRO-2 launch with partitioned (`ds_id`) parameters still gets
no_grad;
- the existing DeepSpeed cases (env without a stage, accelerator state
without a plugin) still get no_grad.

5 of the new cases fail on main; 24 pass here.
`test_deepspeed_zero3.py`, `test_grpo_hidden_states_signal.py`,
`test_fsdp2_native_backend_table.py`, `test_fa2_fast_generate_bypass.py`
and `test_block_swap_auto_ddp.py`: 107 passed.

## Not covered
No real multi-GPU DeepSpeed run here; the decode speed difference on
ZeRO-2 was not measured.

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant