Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Hanb8244124909b
diff --git a/tests/test_fsdp_generation_grad_mode.py b/tests/test_fsdp_generation_grad_mode.py
index 04601c35bc0..b8cce6f0e35 100644
--- a/tests/test_fsdp_generation_grad_mode.py
+++ b/tests/test_fsdp_generation_grad_mode.py
@@ -91,3 +91,29 @@ def test_fsdp2_under_inference_mode_is_the_reported_failure(no_launcher, tmp_pat
"""Negative control: what the helper returned before unsloth#3551."""
with pytest.raises(RuntimeError, match = "[Ii]nference tensor"):
_fsdp2_generate_then_train(tmp_path, lambda model: torch.inference_mode())
+
+
+ "value, inference",
+ [("true", False), ("1", False), ("false", True), ("", True)],
+)
+def test_deepspeed_launch_scores_under_no_grad(no_launcher, value, inference):
+ """ZeRO-3 keeps gathered persistent params: inference-mode gathers poison backward."""
+ no_launcher.setenv("ACCELERATE_USE_DEEPSPEED", value)
+ assert _mode_inside(torch.nn.Linear(2, 2)) == (inference, False)
+
+
+def test_zero3_partitioned_model_scores_under_no_grad(no_launcher):
+ no_launcher.delenv("ACCELERATE_USE_DEEPSPEED", raising = False)
+ model = torch.nn.Linear(2, 2)
+ model.weight.ds_id = 0
+ assert _mode_inside(model) == (False, False)
+
+
+def test_deepspeed_accelerator_state_scores_under_no_grad(no_launcher):
+ state = pytest.importorskip("accelerate.state")
+ no_launcher.delenv("ACCELERATE_USE_DEEPSPEED", raising = False)
+ no_launcher.setattr(
+ state.AcceleratorState, "_shared_state", {"distributed_type": "DistributedType.DEEPSPEED"}
+ )
+ assert _mode_inside(torch.nn.Linear(2, 2)) == (False, False)
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 4a47f1dbbc0..03d534edbbd 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -8141,6 +8141,19 @@ def _get_inference_mode_context_manager(model: torch.nn.Module):
)
if isinstance(shared_state, dict) and "FSDP" in str(shared_state.get("distributed_type", "")):
return torch.no_grad()
+ # ZeRO-3 keeps small persistent gathered params, so the same poisoning applies.
+ if os.environ.get("ACCELERATE_USE_DEEPSPEED", "").strip().lower() in ("1", "true", "yes", "on"):
+ return torch.no_grad()
+ if isinstance(shared_state, dict) and "DEEPSPEED" in str(
+ shared_state.get("distributed_type", "")
+ ):
+ return torch.no_grad()
+ try:
+ first = next(iter(model.parameters()), None)
+ except Exception:
+ first = None
+ if first is not None and hasattr(first, "ds_id"):
+ return torch.no_grad()
return torch.inference_mode()
diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py
index cfa5c9bae97..058c7e15523 100644
--- a/unsloth/models/rl_replacements.py
+++ b/unsloth/models/rl_replacements.py
@@ -2619,17 +2619,43 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):
)
lm_head_bias = None
_head_log_softmax = chunked_hidden_states_selective_log_softmax
+ # ZeRO-3 released the head after the forward: score with one gathered read-only copy.
+ _zero3_head = None
+ try:
+ from unsloth_zoo.fused_losses.cross_entropy_loss import (
+ unsloth_zero3_gathered,
+ unsloth_zero3_partitioned,
+ )
+ except (ImportError, NotImplementedError):
+ # Older zoo, or zoo refusing to import without an accelerator (CPU gloo workers).
+ pass
+ else:
+ if unsloth_zero3_partitioned(lm_head) or unsloth_zero3_partitioned(
+ getattr(output_embeddings, "bias", None)
+ ):
+ _zero3_head = (
+ unsloth_zero3_gathered(lm_head),
+ unsloth_zero3_gathered(getattr(output_embeddings, "bias", None)),
+ )
+ lm_head = _zero3_head[0]
+ if lm_head_bias is not None:
+ lm_head_bias = _zero3_head[1]
def chunked_hidden_states_selective_log_softmax(
hidden_states, _lm_head, *args, **kwargs
):
# FSDP2's forward hooks replace Parameters. Read the current head
# at projection time, including the bias, instead of retaining a shard.
+ if _zero3_head is not None:
+ head_weight, head_bias = _zero3_head
+ else:
+ head_weight = output_embeddings.weight
+ head_bias = getattr(output_embeddings, "bias", None)
if UNSLOTH_ZOO_HAS_HEAD_BIAS:
- kwargs["lm_head_bias"] = getattr(output_embeddings, "bias", None)
+ kwargs["lm_head_bias"] = head_bias
return _head_log_softmax(
hidden_states,
- output_embeddings.weight,
+ head_weight,
*args,
**kwargs,
)