Skip to content

Generation keeps inference_mode on DeepSpeed ZeRO-1/2; only ZeRO-3 needs no_grad - #14673

Merged
danielhanchen merged 6 commits into
mainfrom
zero3-only-no-grad-generate
Oct 25, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
zero3-only-no-grad-generate

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

#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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-25T05:35:01.381860Z 0598849 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 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: 183be52060

ℹ️ 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/_utils.py Outdated
"yes",
"on",
) or (isinstance(shared_state, dict) and "DEEPSPEED" in str(shared_state.get("distributed_type", "")))
if deepspeed and _deepspeed_zero_stage(shared_state) in (None, 3):

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 Include the stage helper in generated GRPO modules

When a generated GRPO trainer runs under any DeepSpeed launch, deepspeed is true and this call raises NameError: name '_deepspeed_zero_stage' is not defined. unsloth/models/rl_replacements.py only appends inspect.getsource(_get_inference_mode_context_manager) to RL_PRE_ITEMS["grpo_trainer"], so the newly extracted helper is absent from the generated module even though the copied function references it. Include the helper in the generated preamble (or keep this logic self-contained) so DeepSpeed GRPO generation and log-prob scoring can run.

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.

Fixed in 512ca4b. The stage read now lives inside _get_inference_mode_context_manager instead of a separate helper, so the source rl_replacements copies into the generated GRPO trainer is self-contained. A test parses the function's own source and checks it calls no module-level helper.

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.

Fixed in 512ca4b: the stage read is inlined into _get_inference_mode_context_manager, so the source copied into the generated GRPO trainer is self-contained (test_the_grpo_preamble_copy_is_self_contained).

Comment thread unsloth/models/_utils.py Outdated
plugins = shared_state.get("deepspeed_plugins") if isinstance(shared_state, dict) else None
if plugins is not None and not isinstance(plugins, dict):
plugins = {"default": plugins}
for plugin in (plugins or {}).values():

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Read only the selected DeepSpeed plugin

When Accelerator is configured with multiple DeepSpeed plugins and the selected plugin uses ZeRO-2 while an inactive plugin uses ZeRO-3, iterating over every plugin adds stage 3 and forces no_grad, so the optimization introduced by this change silently disappears. Accelerate marks exactly one plugin as selected, and the existing deepspeed_zero_stage() implementation in unsloth/models/loader_utils.py already filters on plugin.selected; apply the same selection here instead of combining active and inactive configurations.

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.

Fixed in 512ca4b. A plugin with selected=False is skipped, matching deepspeed_zero_stage() in loader_utils.py, so an inactive ZeRO-3 plugin no longer forces no_grad on a ZeRO-2 run. Test: an active stage-2 plugin beside an inactive stage-3 one keeps inference mode.

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.

Fixed in 512ca4b: plugins whose selected flag is False are skipped (test_only_the_selected_deepspeed_plugin_counts).

… the selected DeepSpeed plugin counts

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 059884943e

ℹ️ 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 d4a92bb into main Oct 25, 2026
29 of 37 checks passed
@danielhanchen
danielhanchen deleted the zero3-only-no-grad-generate branch October 25, 2026 08:54
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