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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Follow-ups to the GRPO reward locals and FSDP2 mixed precision merges (#14023)
Daniel Han029bc4ac7e9d
diff --git a/tests/test_fsdp2_config.py b/tests/test_fsdp2_config.pyindex 7543bdd840a..6eb222b4004 100644--- a/tests/test_fsdp2_config.py+++ b/tests/test_fsdp2_config.py@@ -62,6 +62,16 @@ def test_accelerates_auto_policy_reduces_in_fp32(dtype, name):assert acc.state.fsdp_plugin.mixed_precision_policy is policy[email protected]("dtype,name", [(torch.float16, "fp16"), (torch.bfloat16, "bf16")])+def test_torch_26_normalized_auto_policy_still_reduces_in_fp32(dtype, name):+ # torch 2.6 MixedPrecisionPolicy.__post_init__ stores reduce_dtype None when it equals param_dtype.+ auto = MixedPrecisionPolicy(param_dtype = dtype, reduce_dtype = dtype, output_dtype = dtype)+ object.__setattr__(auto, "reduce_dtype", None)+ policy = fsdp2.fill_fsdp2_mixed_precision(_accelerator(auto, name))+ assert policy.reduce_dtype == torch.float32+ assert policy.output_dtype is None++def test_a_policy_the_user_wrote_is_left_alone():user = MixedPrecisionPolicy(param_dtype = torch.float16, reduce_dtype = torch.float16)acc = _accelerator(user, "bf16", auto = False)diff --git a/tests/test_grpo_reward_locals_cycle.py b/tests/test_grpo_reward_locals_cycle.pynew file mode 100644index 00000000000..52640e69ab2--- /dev/null+++ b/tests/test_grpo_reward_locals_cycle.py@@ -0,0 +1,81 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The GRPO reward rewrite keeps locals() in a name. On CPython <= 3.12 a later locals() call in the+same frame stores that dict in itself, so every rollout tensor of the step outlives the call until+the cyclic GC runs. The name must be gone before any later locals() call."""++import ast+import inspect+import textwrap++import pytest++from unsloth.models.rl_replacements import grpo_trainer__generate_and_score_completions+++def _rewritten():+ trl_grpo = pytest.importorskip("trl.trainer.grpo_trainer")+ source = textwrap.dedent(+ inspect.getsource(trl_grpo.GRPOTrainer._generate_and_score_completions)+ )+ source = textwrap.indent(source, " ")+ out = grpo_trainer__generate_and_score_completions("_generate_and_score_completions", source)+ if "_unsloth_reward_locals = locals()" not in out:+ pytest.skip("this TRL has no reward call for the rewrite to anchor on")+ return textwrap.dedent(out)+++def test_reward_locals_alias_is_deleted_before_the_next_locals_call():+ tree = ast.parse(_rewritten())+ lines = sorted(+ (node.lineno, kind)+ for node in ast.walk(tree)+ for kind in (+ ("bind",)+ if isinstance(node, ast.Assign)+ and any(+ isinstance(t, ast.Name) and t.id == "_unsloth_reward_locals" for t in node.targets+ )+ else ("del",)+ if isinstance(node, ast.Delete)+ and any(+ isinstance(t, ast.Name) and t.id == "_unsloth_reward_locals" for t in node.targets+ )+ else ("locals",)+ if isinstance(node, ast.Call) and getattr(node.func, "id", None) == "locals"+ else ()+ )+ )+ bind = next(line for line, kind in lines if kind == "bind")+ deleted = [line for line, kind in lines if kind == "del" and line > bind]+ assert deleted, lines+ # Every locals() call after the binding's own line comes after the del.+ assert not [+ line for line, kind in lines if kind == "locals" and bind < line < deleted[0]+ ], lines+++def test_frame_dict_is_not_kept_alive_after_return():+ import gc+ import weakref++ class Tensor:+ pass++ def step():+ big = Tensor()+ ref = weakref.ref(big)+ _unsloth_reward_locals = locals()+ _unsloth_reward_locals.get("completions_text")+ del _unsloth_reward_locals+ locals().get("tool_mask")+ return ref++ enabled = gc.isenabled()+ gc.disable()+ try:+ assert step()() is None+ finally:+ if enabled:+ gc.enable()diff --git a/unsloth/models/fsdp2.py b/unsloth/models/fsdp2.pyindex d86c79a1b3e..306f4402c63 100644--- a/unsloth/models/fsdp2.py+++ b/unsloth/models/fsdp2.py@@ -119,7 +119,8 @@ def fill_fsdp2_mixed_precision(accelerator):return policyif (policy.param_dtype != compute- or policy.reduce_dtype != compute+ # torch 2.6 stores reduce_dtype None when it equals param_dtype; both reduce in compute.+ or policy.reduce_dtype not in (None, compute)or getattr(policy, "output_dtype", None) not in (None, compute)):return policydiff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex d48d60bec4d..dc563832370 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -2078,7 +2078,10 @@ def grpo_trainer__generate_and_score_completions(function_name, function):" completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)\n"" rewards_per_func = self._calculate_rewards(inputs, prompts_text, completions_text, completion_ids_list)\n"" else:\n"- " rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)"+ " rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)\n"+ # On CPython <= 3.12 a later locals() call would store this frame dict in itself, a+ # cycle that keeps every rollout tensor alive until the cyclic GC runs.+ " del _unsloth_reward_locals")function = function.replace(string_to_find, replacement_string)