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
Keep an explicitly requested float32 model in float32 without bfloat16 (#7867)
Daniel Han85a036a1958e
diff --git a/.gitignore b/.gitignoreindex 5797eaa47c6..433d082ee53 100644--- a/.gitignore+++ b/.gitignore@@ -247,3 +247,6 @@ llama.cpp/async_task_outputs/temp/logs/++# Audio fixture downloaded by tests/saving/text_to_speech_models at import time.+Speech_12dB_s16.flacdiff --git a/tests/saving/text_to_speech_models/test_whisper.py b/tests/saving/text_to_speech_models/test_whisper.pyindex a835b58f8c1..ad1bfdb661a 100644--- a/tests/saving/text_to_speech_models/test_whisper.py+++ b/tests/saving/text_to_speech_models/test_whisper.py@@ -1,3 +1,4 @@+# ruff: noqa# tests/saving scripts run their whole body at import, so plain pytest# collection would download checkpoints and train. Skip unless opted in.import sys as _sys@@ -11,16 +12,26 @@ _require_opt_in("GPU + Hub saving script; its body runs at import.",)-from unsloth import FastLanguageModel, FastModel-from transformers import WhisperForConditionalGeneration, WhisperProcessor-import torch+import pytest++try:+ # unsloth first, so it can patch transformers/peft+ from unsloth import FastLanguageModel, FastModel+ from transformers import WhisperForConditionalGeneration, WhisperProcessor+ import torch+ from peft import PeftModel+ import requests+except ImportError as exc:+ # Imported at collection time, so an absent runtime dep (triton on the+ # Windows CI runner) is a collection error that reports no results at all.+ pytest.skip(+ f"requires the full unsloth runtime: {exc}",+ allow_module_level = True,+ )-# ruff: noqaimport sysfrom pathlib import Path-from peft import PeftModelimport warnings-import requestsREPO_ROOT = Path(__file__).parents[3]@@ -35,9 +46,9 @@ require_python_package("soundfile")import soundfile as sf-print(f"\n{'='*80}")+print(f"\n{'=' * 80}")print("π SECTION 1: Loading Model and LoRA Adapters")-print(f"{'='*80}")+print(f"{'=' * 80}")model, tokenizer = FastModel.from_pretrained(@@ -75,17 +86,17 @@ model = FastModel.get_peft_model(print("β Model and LoRA adapters loaded successfully!")-print(f"\n{'='*80}")+print(f"\n{'=' * 80}")print("π SECTION 2: Checking Model Class Type")-print(f"{'='*80}")+print(f"{'=' * 80}")assert isinstance(model, PeftModel), "Model should be an instance of PeftModel"print("β Model is an instance of PeftModel!")-print(f"\n{'='*80}")+print(f"\n{'=' * 80}")print("π SECTION 3: Checking Config Model Class Type")-print(f"{'='*80}")+print(f"{'=' * 80}")def find_lora_base_model(model_to_inspect):@@ -105,9 +116,9 @@ assert (print("β config_model returns correct Base Model class:", str(base_model_class))-print(f"\n{'='*80}")+print(f"\n{'=' * 80}")print("π SECTION 4: Saving and Merging Model")-print(f"{'='*80}")+print(f"{'=' * 80}")with warnings.catch_warnings():warnings.simplefilter("error") # Treat warnings as errors@@ -117,9 +128,9 @@ with warnings.catch_warnings():except Exception as e:assert False, f"Model saving/merging failed with exception: {e}"-print(f"\n{'='*80}")+print(f"\n{'=' * 80}")print("π SECTION 5: Loading Model for Inference")-print(f"{'='*80}")+print(f"{'=' * 80}")model, tokenizer = FastModel.from_pretrained(@@ -137,9 +148,9 @@ model, tokenizer = FastModel.from_pretrained(print("β Model loaded for inference successfully!")-print(f"\n{'='*80}")+print(f"\n{'=' * 80}")print("π SECTION 6: Downloading Sample Audio File")-print(f"{'='*80}")+print(f"{'=' * 80}")audio_url = "https://upload.wikimedia.org/wikipedia/commons/5/5b/Speech_12dB_s16.flac"audio_file = "Speech_12dB_s16.flac"@@ -154,11 +165,17 @@ try:f.write(response.content)print("β Audio file downloaded successfully!")except Exception as e:- assert False, f"Failed to download audio file: {e}"--print(f"\n{'='*80}")+ # Runs at import, so a failure here is a collection error and the whole file+ # reports no results. Wikimedia rate-limits this URL (429 in a batch run) and+ # a fixture we could not fetch says nothing about unsloth, so skip.+ pytest.skip(+ f"could not download the test audio fixture from {audio_url}: {e}",+ allow_module_level = True,+ )++print(f"\n{'=' * 80}")print("π SECTION 7: Running Inference")-print(f"{'='*80}")+print(f"{'=' * 80}")from transformers import pipelinediff --git a/tests/test_float32_no_fp16_autocast.py b/tests/test_float32_no_fp16_autocast.pynew file mode 100644index 00000000000..507fdd63bdb--- /dev/null+++ b/tests/test_float32_no_fp16_autocast.py@@ -0,0 +1,312 @@+# Unsloth Zoo - Utilities for Unsloth+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.+#+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published+# by the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.++"""A float32 model on a GPU without bf16 must not be wrapped in fp16 autocast.++Spark_TTS_(0_5B) loads with `dtype = torch.float32` and sets `fp16 = False,+bf16 = False`. On a T4 it logged [nan] x 7 and then died at inference inside+torch.multinomial, which refuses a distribution containing NaN.++The cause is upstream of the sampler: rl.py reads "neither flag set" as "user+did not choose" and picks the autocast dtype itself, which on a T4 is float16.+float16 carries five exponent bits against float32's eight, so a value the+model was loaded wide enough to hold overflows to inf and then NaN. bf16 GPUs+keep the autocast, since bf16 has float32's exponent range; only float16 is+unsafe and only that case changes.++The block lives in rl.py as a string compiled into the generated trainer, so+these tests pull the literal out and execute it against fake `args` / `model`+objects. No GPU, no network, no trl import.+"""++import ast+import types+from pathlib import Path++import pytest+import torch++REPO_ROOT = Path(__file__).resolve().parents[1]+RL_PY = REPO_ROOT / "unsloth" / "models" / "rl.py"+++def _mixed_precision_source() -> str:+ """Extract the `mixed_precision = (...)` string literal from rl.py."""+ src = RL_PY.read_text(encoding = "utf-8")+ tree = ast.parse(src)+ for node in ast.walk(tree):+ if not isinstance(node, ast.Assign):+ continue+ targets = [t.id for t in node.targets if isinstance(t, ast.Name)]+ if "mixed_precision" not in targets:+ continue+ if isinstance(node.value, (ast.Constant, ast.JoinedStr, ast.BinOp)):+ pass+ try:+ return ast.literal_eval(node.value)+ except ValueError:+ continue+ raise AssertionError("mixed_precision block not found in rl.py")+++MP_SRC = _mixed_precision_source()+++def _get_dtype(dtype):+ """Stand-in for unsloth_zoo.utils._get_dtype: accept a dtype or its name."""+ if isinstance(dtype, torch.dtype):+ return dtype+ return getattr(torch, str(dtype).replace("torch.", ""))+++class _Args:+ def __init__(+ self,+ fp16 = False,+ bf16 = False,+ ):+ self.fp16 = fp16+ self.bf16 = bf16+++def _run(+ model_dtype,+ bf16_supported,+ fp16 = False,+ bf16 = False,+ force_float32 = "0",+ full_finetuning = "0",+ mixed_precision = "float32",+ user_float32 = None,+):+ """Execute the block and report what it decided."""+ config = types.SimpleNamespace(dtype = model_dtype, torch_dtype = model_dtype)+ # from_pretrained records this only for an explicit dtype = torch.float32.+ # Defaulting it from the model dtype keeps each test's intent readable.+ model = types.SimpleNamespace(+ config = config,+ _unsloth_user_float32 = (+ (model_dtype is torch.float32) if user_float32 is None else user_float32 == "1"+ ),+ )+ args = _Args(fp16 = fp16, bf16 = bf16)+ env = {+ "UNSLOTH_FORCE_FLOAT32": force_float32,+ "UNSLOTH_ENABLE_FULL_FINETUNING": full_finetuning,+ "UNSLOTH_MIXED_PRECISION": mixed_precision,+ }+ fake_os = types.SimpleNamespace(environ = env)++ ns = {+ "torch": torch,+ "os": fake_os,+ "args": args,+ "model": model,+ "print": lambda *a, **k: None,+ }+ # The block imports device_is_bf16_supported and falls back to+ # torch.cuda.is_bf16_supported; make both answer the same way.+ real_cuda = torch.cuda+ torch.cuda = types.SimpleNamespace(is_bf16_supported = lambda: bf16_supported)+ import sys++ # Stub the PARENT too: `from unsloth_zoo.device_type import x` imports+ # unsloth_zoo first, and a raising package __init__ would silently route the+ # block through the torch.cuda fallback instead of the branch under test.+ mod = types.ModuleType("unsloth_zoo.device_type")+ mod.device_is_bf16_supported = lambda: bf16_supported+ utils = types.ModuleType("unsloth_zoo.utils")+ utils._get_dtype = _get_dtype+ parent = types.ModuleType("unsloth_zoo")+ parent.__path__ = [] # make it a package, not a plain module+ parent.device_type = mod+ parent.utils = utils+ names = ("unsloth_zoo", "unsloth_zoo.device_type", "unsloth_zoo.utils")+ saved = {k: sys.modules.get(k) for k in names}+ sys.modules["unsloth_zoo"] = parent+ sys.modules["unsloth_zoo.device_type"] = mod+ sys.modules["unsloth_zoo.utils"] = utils+ try:+ exec(MP_SRC, ns)+ finally:+ torch.cuda = real_cuda+ for k, v in saved.items():+ if v is None:+ sys.modules.pop(k, None)+ else:+ sys.modules[k] = v+ # The fallback would mask a broken branch, so prove the stub was used.+ assert ns["_bf16_supported"] is mod.device_is_bf16_supported+ return args, env+++# ---- the bug -------------------------------------------------------------+++def test_float32_model_on_t4_stays_float32():+ args, env = _run(torch.float32, bf16_supported = False)+ assert args.fp16 is False, "float32 model must not get float16 autocast"+ assert args.bf16 is False+ assert env["ACCELERATE_MIXED_PRECISION"] == "no"+++def test_float32_full_finetuning_on_t4_stays_float32():+ # Spark_TTS exactly: full_finetuning = True, both flags off, no bf16.+ args, env = _run(torch.float32, bf16_supported = False, full_finetuning = "1")+ assert (args.fp16, args.bf16) == (False, False)+ assert env["ACCELERATE_MIXED_PRECISION"] == "no"+++# ---- everything that must NOT change -------------------------------------+++def test_float32_model_on_bf16_gpu_still_autocasts():+ # bf16 shares float32's exponent range, so this stays safe and cheap.+ args, env = _run(torch.float32, bf16_supported = True)+ assert args.bf16 is True and args.fp16 is False+ assert env["ACCELERATE_MIXED_PRECISION"] == "bf16"+++def test_float16_model_on_t4_still_gets_fp16_autocast():+ args, env = _run(torch.float16, bf16_supported = False)+ assert args.fp16 is True and args.bf16 is False+ assert env["ACCELERATE_MIXED_PRECISION"] == "fp16"+++def test_bfloat16_model_on_bf16_gpu_unchanged():+ args, env = _run(torch.bfloat16, bf16_supported = True)+ assert args.bf16 is True and args.fp16 is False+ assert env["ACCELERATE_MIXED_PRECISION"] == "bf16"+++def test_explicit_fp16_on_a_float32_model_is_obeyed():+ # An explicit request is a choice, not a default; leave it alone.+ args, env = _run(torch.float32, bf16_supported = False, fp16 = True)+ assert args.fp16 is True+ assert env["ACCELERATE_MIXED_PRECISION"] == "fp16"+++def test_explicit_bf16_on_a_float32_model_is_obeyed():+ args, env = _run(torch.float32, bf16_supported = True, bf16 = True)+ assert args.bf16 is True+ assert env["ACCELERATE_MIXED_PRECISION"] == "bf16"+++def test_force_float32_models_take_the_earlier_branch():+ # Gemma3 / gpt-oss on a T4: force_float32 wins before the new branch and+ # already lands on pure float32, so the outcome is identical either way.+ args, env = _run(torch.float32, bf16_supported = False, force_float32 = "1")+ assert (args.fp16, args.bf16) == (False, False)+ assert env["ACCELERATE_MIXED_PRECISION"] == "no"+++def test_force_float32_full_finetuning_on_bf16_gpu_keeps_bf16_autocast():+ # The documented fast path: master weights stay float32, autocast is bf16.+ args, env = _run(torch.float32, bf16_supported = True, force_float32 = "1", full_finetuning = "1")+ assert args.bf16 is True and args.fp16 is False+ assert env["ACCELERATE_MIXED_PRECISION"] == "bf16"+++def test_bfloat16_mixed_precision_mode_unchanged():+ # UNSLOTH_MIXED_PRECISION = bfloat16 does no autocasting at all.+ args, env = _run(torch.bfloat16, bf16_supported = True, mixed_precision = "bfloat16")+ assert (args.fp16, args.bf16) == (False, False)+ assert env["ACCELERATE_MIXED_PRECISION"] == "no"+++def test_upcast_float32_on_a_v100_still_gets_fp16_autocast():+ """The float32 the model was UPCAST to is not a request for float32.++ Full finetuning upcasts trainable weights to float32 by itself, and+ float16 autocast over float32 master weights is the ordinary V100/T4+ mixed-precision recipe (issue #4082). Only an explicit+ `dtype = torch.float32` at load time may suppress it, which is why the+ new branch is gated on the recorded request rather than on the dtype.+ """+ args, env = _run(torch.float32, bf16_supported = False, full_finetuning = "1", user_float32 = "0")+ assert (args.fp16, args.bf16) == (True, False)+ assert env["ACCELERATE_MIXED_PRECISION"] == "fp16"+++def test_loaders_record_the_explicit_request():+ """Every public entry point, since only the outermost one sees the+ argument as the caller wrote it."""+ for rel in ("unsloth/models/loader.py", "unsloth/models/vision.py"):+ src = (REPO_ROOT / rel).read_text(encoding = "utf-8")+ assert "_requested_float32(dtype)" in src, rel+ assert "_mark_requested_float32(" in src, rel+++def test_the_legacy_language_model_path_records_it_too():+ """llama, mistral, gemma, gemma2, qwen2 and qwen3 LoRA/QLoRA loads go+ through dispatch_model.from_pretrained, which is neither of the two loaders+ that used to record this. Those are most of the notebooks."""+ src = (REPO_ROOT / "unsloth" / "models" / "loader.py").read_text(encoding = "utf-8")+ tree = ast.parse(src)+ cls = next(+ n for n in ast.walk(tree) if isinstance(n, ast.ClassDef) and n.name == "FastLanguageModel"+ )+ fn = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "from_pretrained")+ body = ast.unparse(fn)+ assert "_requested_float32(dtype)" in body+ # Every exit, including the two that hand off to FastModel: it would+ # otherwise record the dtype we derived from a 4bit compute dtype.+ returns = [+ ast.unparse(n) for n in ast.walk(fn) if isinstance(n, ast.Return) and n.value is not None+ ]+ assert returns, "expected the loader to return a model"+ for statement in returns:+ assert "_mark_requested_float32(" in statement, statement+++def test_the_text_diffusion_path_records_it_too():+ """DiffusionGemma leaves FastModel through _dispatch_diffusion, which returns+ before the stamping at the end of from_pretrained. A `dtype = torch.float32`+ load on a T4 would otherwise reach the trainer unmarked and autocast to+ float16, which is the overflow this whole branch exists to avoid."""+ src = (REPO_ROOT / "unsloth" / "models" / "loader.py").read_text(encoding = "utf-8")+ tree = ast.parse(src)+ fn = next(+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.FunctionDef) and n.name == "_dispatch_diffusion"+ )+ returns = [ast.unparse(n) for n in ast.walk(fn) if isinstance(n, ast.Return)]+ assert returns, "expected the diffusion dispatch to return a model"+ for statement in returns:+ assert "_mark_requested_float32(model, user_float32)" in statement, statement+++def test_the_request_is_read_from_the_model_not_the_environment():+ """A process-global would describe whichever model loaded last, so a+ program that loads two before building a trainer would train the first+ with the second's precision."""+ assert "_unsloth_user_float32" in MP_SRC+ assert "UNSLOTH_USER_FLOAT32" not in MP_SRC+++def test_a_model_without_the_marker_keeps_the_old_behaviour():+ """Anything the loaders did not touch must not opt into the new branch."""+ args, _ = _run(torch.float32, bf16_supported = False, user_float32 = "0")+ assert (args.fp16, args.bf16) == (True, False)+++def test_block_still_compiles():+ compile(MP_SRC, "mixed_precision", "exec")+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))diff --git a/tests/test_grpo_autocast_disabled.py b/tests/test_grpo_autocast_disabled.pynew file mode 100644index 00000000000..c5ecafac7b0--- /dev/null+++ b/tests/test_grpo_autocast_disabled.py@@ -0,0 +1,262 @@+# Unsloth Zoo - Utilities for Unsloth+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.+#+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published+# by the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.++"""ACCELERATE_MIXED_PRECISION = 'no' is a value, not an absence.++The GRPO replacements read it as a two-way switch, fp16 else bfloat16, so 'no'+comes out as bfloat16 and autocast is entered anyway. On a T4 or V100 torch does+not merely ignore that, it raises++ RuntimeError: Current CUDA Device does not support bfloat16.+ Please switch dtype to float16.++Two callers set 'no' and both land on exactly those GPUs: full finetuning+already did, and rl.py now does for a model explicitly loaded in float32, so the+branch meant to keep training in float32 could instead stop it. The fix is+`enabled`, not a different dtype: torch only validates bfloat16 when autocast is+on, and turning it off is what 'no' means.+"""++import ast+import re+import sys+import textwrap+from pathlib import Path++import pytest+import torch++REPO_ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(REPO_ROOT))++RL_REPLACEMENTS = REPO_ROOT / "unsloth" / "models" / "rl_replacements.py"+SRC = RL_REPLACEMENTS.read_text(encoding = "utf-8")+++# ---- the premise ---------------------------------------------------------+#+# Every check drives torch.amp.autocast(device_type = "cuda"), and on a CPU+# runner torch hands back a no-op instead. Claiming the device is present is+# what lets these run anywhere; only torch's dispatch decisions are needed.+++class _pretend_cuda:+ """torch.cuda answering as a card without bfloat16, or with it."""++ def __init__(self, has_bf16):+ self.has_bf16 = has_bf16++ def __enter__(self):+ self._saved = (torch.cuda.is_available, torch.cuda.is_bf16_supported)+ torch.cuda.is_available = lambda *args, **kwargs: True+ torch.cuda.is_bf16_supported = lambda *args, **kwargs: self.has_bf16+ return self++ def __exit__(self, *exc):+ torch.cuda.is_available, torch.cuda.is_bf16_supported = self._saved+++def test_bfloat16_autocast_raises_without_hardware_support():+ """Guards everything below: if torch ever downgraded this to a warning,+ the bug would be a silent precision change instead of a crash, and these+ tests would be asserting the wrong thing."""+ with _pretend_cuda(has_bf16 = False):+ with pytest.raises(RuntimeError, match = "does not support bfloat16"):+ with torch.amp.autocast(device_type = "cuda", dtype = torch.bfloat16):+ pass+++def test_disabling_autocast_skips_that_check():+ with _pretend_cuda(has_bf16 = False):+ with torch.amp.autocast(device_type = "cuda", dtype = torch.bfloat16, enabled = False):+ pass+++# ---- _prepare_inputs, which is injected as source ------------------------+++def _prepare_inputs_snippet() -> str:+ """The `with` header grpo_trainer__prepare_inputs splices into TRL."""+ start = SRC.index('"with torch.inference_mode(), "')+ end = SRC.index('",\n', start)+ return ast.literal_eval("(" + SRC[start : end + 1] + ")")+++def _autocast_helper_source() -> str:+ """Module level helpers the header calls, mirrored into the generated+ trainer through RL_PRE_ITEMS."""+ parts = [+ ast.get_source_segment(SRC, node)+ for node in ast.parse(SRC).body+ if isinstance(node, ast.FunctionDef) and node.name.startswith("_unsloth_grpo_autocast")+ ]+ assert parts, "expected the shared autocast helper"+ return "\n\n".join(parts)+++def _namespace(env):+ """What the generated trainer module offers the header. `self` carries no+ args here, which is the fallback path; a trainer with args is covered in+ test_grpo_autocast_per_trainer.py."""+ from contextlib import nullcontext++ namespace = {+ "torch": torch,+ "os": type(sys)("os"),+ "nullcontext": nullcontext,+ "self": type("Trainer", (), {})(),+ "seen": [],+ }+ namespace["os"].environ = env+ exec(_autocast_helper_source(), namespace)+ return namespace+++def test_the_injected_snippet_is_valid_python():+ ast.parse(_prepare_inputs_snippet() + "\n pass\n")+++ "precision,has_bf16,expect_enabled",+ [+ # The T4/V100 case, where the bug bites. accelerate never asks for bf16+ # on this hardware, so that pairing is not a case.+ ("no", False, False),+ ("fp16", False, True),+ (None, False, True),+ ("no", True, False),+ ("bf16", True, True),+ ],+)+def test_the_injected_snippet_only_autocasts_when_asked(precision, has_bf16, expect_enabled):+ """Run the real header and check both that it survives and that it did not+ quietly stop autocasting for everyone else."""+ env = {"UNSLOTH_FORCE_FLOAT32": "0"}+ if precision is not None:+ env["ACCELERATE_MIXED_PRECISION"] = precision++ namespace = _namespace(env)+ with _pretend_cuda(has_bf16 = has_bf16):+ exec(+ _prepare_inputs_snippet() + "\n seen.append(torch.is_autocast_enabled('cuda'))\n",+ namespace,+ )+ assert namespace["seen"] == [expect_enabled]+++# ---- _get_per_token_logps and friends, which run as ordinary code --------+++def test_every_autocast_call_passes_enabled():+ """Five call sites share one `self._autocast_dtype`; one left behind would+ still raise, and only on the hardware nobody develops on."""+ calls = re.findall(r"torch\.amp\.autocast\((?:[^()]|\([^()]*\))*\)", SRC)+ using = [c for c in calls if "self._autocast_dtype" in c]+ assert using, "expected the shared autocast dtype to be used"+ missing = [c for c in using if "_autocast_enabled" not in c]+ assert missing == [], missing+++def test_the_flag_is_recorded_beside_the_dtype():+ """Every `_autocast_dtype` assignment must record the flag beside it. Both+ live in the one helper now, the default and the forced float32 override.++ Paired by position rather than by counting a literal spelling: the repo's+ ruff hook is free to collapse either assignment onto one line, and a test+ that pins `= (` would fail on formatting alone while a genuinely missing+ initialiser slipped through.+ """+ lines = SRC.splitlines()+ dtype_at = [i for i, l in enumerate(lines) if "self._autocast_dtype = " in l]+ flag_at = [i for i, l in enumerate(lines) if "self._autocast_enabled = " in l]+ assert len(dtype_at) == 2, dtype_at+ for i in dtype_at:+ assert any(0 < j - i <= 8 for j in flag_at), (i, lines[i].strip())+++def test_reading_it_tolerates_an_older_trainer():+ """The dtype is cached under `hasattr`, so an instance built before this+ change can reach a call site with only half the state."""+ for call in re.findall(r"getattr\(self, \"_autocast_enabled\"[^)]*\)", SRC):+ assert call.endswith("True)"), call+++def test_force_float32_still_autocasts_in_float16():+ """UNSLOTH_FORCE_FLOAT32 models (Gemma3, gpt_oss) are a different case: they+ keep fp16 autocast, so `no` must not swallow them."""+ for match in re.finditer(r'UNSLOTH_FORCE_FLOAT32", "0"\) == "1":\n(.+?)\n\n', SRC, re.S):+ block = match.group(1)+ if "_autocast_dtype" not in block:+ continue+ assert "self._autocast_enabled = True" in block, block+++def test_forced_float32_still_autocasts_in_the_injected_header():+ """UNSLOTH_FORCE_FLOAT32 sets 'no' as well, but wants fp16 autocast, so the+ shared helper overrides both the dtype and the flag for it. Reading 'no'+ alone here would have left Gemma3 and gpt-oss generation in full float32."""+ namespace = _namespace(+ {+ "ACCELERATE_MIXED_PRECISION": "no",+ "UNSLOTH_FORCE_FLOAT32": "1",+ }+ )+ with _pretend_cuda(has_bf16 = False):+ exec(+ _prepare_inputs_snippet()+ + "\n seen.append(torch.get_autocast_dtype('cuda') if torch.is_autocast_enabled('cuda') else None)\n",+ namespace,+ )+ assert namespace["seen"] == [torch.float16]+++def test_chunk_sizing_reads_the_model_dtype_when_autocast_is_off():+ """With autocast off the forward runs in the model's own dtype. That is+ float32 for an explicit float32 load but bfloat16 for pure bfloat16 full+ finetuning, so the flag alone would double the estimate for the latter."""+ line = next(l for l in SRC.splitlines() if "forward_dtype = (" in l)+ block = SRC[SRC.index(line) : SRC.index(line) + 400]+ assert "_autocast_enabled" in block, block+ assert "lm_head.dtype" in block, block+ assert "dtype_bytes = 16 if forward_dtype in" in block, block+++def test_chunk_sizing_by_execution():+ """Both cases, evaluated rather than read: pure bfloat16 full finetuning+ keeps 16, an explicit float32 load gets 32."""+ for head_dtype, expected in ((torch.bfloat16, 16), (torch.float32, 32)):+ scope = {+ "torch": torch,+ "self": type(+ "T",+ (),+ {+ "_autocast_dtype": torch.bfloat16,+ "_autocast_enabled": False,+ },+ )(),+ "lm_head": torch.zeros(2, 2, dtype = head_dtype),+ }+ line = next(l for l in SRC.splitlines() if "forward_dtype = (" in l)+ start = SRC.index(line)+ end = SRC.index("dtype_bytes = 16 if forward_dtype in", start)+ end = SRC.index("\n", end)+ exec(textwrap.dedent(SRC[start:end]), scope)+ assert scope["dtype_bytes"] == expected, (head_dtype, scope["dtype_bytes"])+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))diff --git a/tests/test_grpo_autocast_per_trainer.py b/tests/test_grpo_autocast_per_trainer.pynew file mode 100644index 00000000000..59e9e29732e--- /dev/null+++ b/tests/test_grpo_autocast_per_trainer.py@@ -0,0 +1,702 @@+# Unsloth Zoo - Utilities for Unsloth+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.+#+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published+# by the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.++"""The GRPO autocast belongs to a trainer, not to the process.++rl.py records the precision twice: on `args`, which belongs to one trainer, and+in ACCELERATE_MIXED_PRECISION, which every trainer in the process shares. Build+a float32 T4 trainer first (rl.py writes 'no') and a float16 trainer second+(rl.py writes 'fp16'), and the first trainer's generation loop, which reread the+env var every batch, enters a float16 autocast it was explicitly kept out of:+the same overflow to inf and then NaN test_float32_no_fp16_autocast.py prevents.++The rl.py __init__ block and the _prepare_inputs header are pulled out of the+sources as strings and run against fake args / model / trainer objects sharing+one dict as the environment. No GPU, no model download, no trl import; torch.cuda+is made to answer "available, no bfloat16", all the code under test ever asks.+"""++import ast+import re+import sys+import textwrap+import types+from contextlib import nullcontext+from pathlib import Path++import pytest+import torch++REPO_ROOT = Path(__file__).resolve().parents[1]++RL_PY = REPO_ROOT / "unsloth" / "models" / "rl.py"+RL_REPLACEMENTS = REPO_ROOT / "unsloth" / "models" / "rl_replacements.py"+RL_SRC = RL_PY.read_text(encoding = "utf-8")+REPL_SRC = RL_REPLACEMENTS.read_text(encoding = "utf-8")+++# ---- the two pieces of source under test ---------------------------------+++def _mixed_precision_source() -> str:+ """The `mixed_precision = (...)` literal rl.py compiles into __init__."""+ for node in ast.walk(ast.parse(RL_SRC)):+ if not isinstance(node, ast.Assign):+ continue+ if "mixed_precision" not in [t.id for t in node.targets if isinstance(t, ast.Name)]:+ continue+ try:+ return ast.literal_eval(node.value)+ except ValueError:+ continue+ raise AssertionError("mixed_precision block not found in rl.py")+++def _prepare_inputs_snippet() -> str:+ """The `with` header grpo_trainer__prepare_inputs splices into TRL."""+ start = REPL_SRC.index('"with torch.inference_mode(), "')+ end = REPL_SRC.index('",\n', start)+ return ast.literal_eval("(" + REPL_SRC[start : end + 1] + ")")+++def _autocast_helper_source() -> str:+ """Module level helpers the header may call, mirrored into the generated+ trainer through RL_PRE_ITEMS. Empty before those helpers existed."""+ parts = [+ ast.get_source_segment(REPL_SRC, node)+ for node in ast.parse(REPL_SRC).body+ if isinstance(node, ast.FunctionDef) and node.name.startswith("_unsloth_grpo_autocast")+ ]+ return "\n\n".join(parts)+++MP_SRC = _mixed_precision_source()+++class _pretend_cuda:+ """torch.cuda answering as a card without bfloat16, or with it."""++ def __init__(self, has_bf16):+ self.has_bf16 = has_bf16++ def __enter__(self):+ self._saved = (torch.cuda.is_available, torch.cuda.is_bf16_supported)+ torch.cuda.is_available = lambda *args, **kwargs: True+ torch.cuda.is_bf16_supported = lambda *args, **kwargs: self.has_bf16+ return self++ def __exit__(self, *exc):+ torch.cuda.is_available, torch.cuda.is_bf16_supported = self._saved+++# ---- a trainer, as far as any of this code can tell ----------------------+++class _Args:+ """The fields of TrainingArguments that rl.py writes and the header reads.++ transformers < 5 has no `mixed_precision`, and rl.py only assigns it under+ hasattr, so `has_mixed_precision` picks which of the two worlds we are in.+ """++ def __init__(+ self,+ fp16 = False,+ bf16 = False,+ has_mixed_precision = True,+ ):+ self.fp16 = fp16+ self.bf16 = bf16+ if has_mixed_precision:+ self.mixed_precision = "no"+++def _build_trainer(+ env,+ model_dtype,+ bf16_supported,+ fp16 = False,+ bf16 = False,+ user_float32 = None,+ has_mixed_precision = True,+ mark_forced_float32 = True,+ forced_float32 = None,+ mark_full_finetuning = True,+ full_finetuning = None,+ env_override = None,+):+ """Run rl.py's __init__ block for one trainer against the shared env."""+ args = _Args(fp16 = fp16, bf16 = bf16, has_mixed_precision = has_mixed_precision)+ model = types.SimpleNamespace(+ config = types.SimpleNamespace(dtype = model_dtype, torch_dtype = model_dtype),+ _unsloth_user_float32 = (+ (model_dtype is torch.float32) if user_float32 is None else user_float32+ ),+ )+ env.setdefault("UNSLOTH_FORCE_FLOAT32", "0")+ if mark_forced_float32:+ # What from_pretrained stamps on the model. `forced_float32` sets it apart+ # from the env, which is what an earlier load leaves behind.+ model._unsloth_forced_float32 = (+ (env["UNSLOTH_FORCE_FLOAT32"] == "1") if forced_float32 is None else forced_float32+ )+ env.setdefault("UNSLOTH_ENABLE_FULL_FINETUNING", "0")+ if mark_full_finetuning:+ # The other half of the load, stamped the same way and for the same reason.+ model._unsloth_full_finetuning = (+ (env["UNSLOTH_ENABLE_FULL_FINETUNING"] == "1")+ if full_finetuning is None+ else full_finetuning+ )+ env.setdefault("UNSLOTH_MIXED_PRECISION", "float32")+ # What a load between this one and its trainer leaves in the shared environment.+ if env_override:+ env.update(env_override)++ def _get_dtype(dtype):+ return dtype if isinstance(dtype, torch.dtype) else getattr(torch, str(dtype))++ device_type = types.ModuleType("unsloth_zoo.device_type")+ device_type.device_is_bf16_supported = lambda: bf16_supported+ utils = types.ModuleType("unsloth_zoo.utils")+ utils._get_dtype = _get_dtype+ parent = types.ModuleType("unsloth_zoo")+ parent.__path__ = []+ names = ("unsloth_zoo", "unsloth_zoo.device_type", "unsloth_zoo.utils")+ saved = {k: sys.modules.get(k) for k in names}+ sys.modules["unsloth_zoo"] = parent+ sys.modules["unsloth_zoo.device_type"] = device_type+ sys.modules["unsloth_zoo.utils"] = utils+ scope = {+ "torch": torch,+ "os": types.SimpleNamespace(environ = env),+ "args": args,+ "model": model,+ "print": lambda *a, **k: None,+ }+ try:+ with _pretend_cuda(has_bf16 = bf16_supported):+ exec(MP_SRC, scope)+ finally:+ for k, v in saved.items():+ if v is None:+ sys.modules.pop(k, None)+ else:+ sys.modules[k] = v+ assert scope["_bf16_supported"] is device_type.device_is_bf16_supported+ # The trainer, as much of one as the autocast header ever touches.+ return types.SimpleNamespace(args = args, model = model)+++def _generate(trainer, env, has_bf16):+ """Enter the injected _prepare_inputs header once and report the autocast."""+ scope = {+ "torch": torch,+ "os": types.SimpleNamespace(environ = env),+ "nullcontext": nullcontext,+ "self": trainer,+ "seen": [],+ }+ helpers = _autocast_helper_source()+ if helpers:+ exec(helpers, scope)+ body = (+ "\n seen.append((torch.is_autocast_enabled('cuda'), "+ "torch.get_autocast_dtype('cuda') if torch.is_autocast_enabled('cuda') else None))\n"+ )+ with _pretend_cuda(has_bf16 = has_bf16):+ exec(_prepare_inputs_snippet() + body, scope)+ return scope["seen"][0]+++# ---- the bug -------------------------------------------------------------++[email protected]("has_mixed_precision", [True, False])+def test_a_later_trainer_cannot_re_enable_this_trainers_autocast(has_mixed_precision):+ """First trainer: float32 on a card without bfloat16, so rl.py writes 'no'.+ Second trainer: an ordinary float16 model, so rl.py writes 'fp16' over it.+ The first trainer has not generated a single batch yet."""+ env = {}+ first = _build_trainer(+ env, torch.float32, bf16_supported = False, has_mixed_precision = has_mixed_precision+ )+ assert env["ACCELERATE_MIXED_PRECISION"] == "no"++ _build_trainer(+ env, torch.float16, bf16_supported = False, has_mixed_precision = has_mixed_precision+ )+ assert env["ACCELERATE_MIXED_PRECISION"] == "fp16", "the second trainer owns the env now"++ enabled, dtype = _generate(first, env, has_bf16 = False)+ assert enabled is False, "float32 trainer was pulled into the other trainer's fp16 autocast"+ assert dtype is None+++def test_the_decision_survives_a_trainer_built_after_the_first_batch():+ """Latching on first use is not enough on its own; check the other order+ too, where the first trainer has already generated once."""+ env = {}+ first = _build_trainer(env, torch.float32, bf16_supported = False)+ assert _generate(first, env, has_bf16 = False) == (False, None)++ _build_trainer(env, torch.float16, bf16_supported = False)+ assert _generate(first, env, has_bf16 = False) == (False, None)+++def test_two_trainers_in_one_process_each_keep_their_own_answer():+ env = {}+ first = _build_trainer(env, torch.float32, bf16_supported = False)+ second = _build_trainer(env, torch.float16, bf16_supported = False)++ assert _generate(first, env, has_bf16 = False) == (False, None)+ assert _generate(second, env, has_bf16 = False) == (True, torch.float16)+++def test_a_later_load_cannot_take_this_trainers_float16_autocast_away():+ """UNSLOTH_FORCE_FLOAT32 is the other process wide answer in play here.++ from_pretrained clears it on every load and sets it again only for the+ families that need it, so a Gemma3 trainer built first and a plain model+ loaded second leaves '0' behind. Reading it at the first generation would+ then drop the float16 autocast that rl.py's 'no' was written expecting,+ and run generation in full float32.+ """+ env = {"UNSLOTH_FORCE_FLOAT32": "1"}+ first = _build_trainer(env, torch.float32, bf16_supported = False)+ assert env["ACCELERATE_MIXED_PRECISION"] == "no"++ # A second from_pretrained, before the first trainer generates.+ env["UNSLOTH_FORCE_FLOAT32"] = "0"+ _build_trainer(env, torch.float16, bf16_supported = False)++ assert _generate(first, env, has_bf16 = False) == (True, torch.float16)+++def test_a_forced_float32_model_keeps_the_bfloat16_the_trainer_chose():+ """A forced float32 family loaded with an explicit dtype = torch.float16 on a+ bfloat16 card stamps the model (loader.py:1791, loader.py:2148) even though+ it loads in bfloat16. Full finetuning on that card then lets rl.py:1013 skip+ force_float32 and pick bf16 on purpose, so the stamp must not pull generation+ back into the float16 that the forced list exists to avoid."""+ env = {"UNSLOTH_FORCE_FLOAT32": "1", "UNSLOTH_ENABLE_FULL_FINETUNING": "1"}+ trainer = _build_trainer(env, torch.bfloat16, bf16_supported = True)+ assert env["ACCELERATE_MIXED_PRECISION"] == "bf16"+ assert _generate(trainer, env, has_bf16 = True) == (True, torch.bfloat16)+++def test_a_later_load_cannot_take_full_finetunings_bfloat16_away():+ """UNSLOTH_ENABLE_FULL_FINETUNING is the third process wide answer in play.++ from_pretrained writes it on every load, so a LoRA model loaded after a+ forced float32 family that was loaded for full finetuning leaves '0' behind.+ The trainer then pairs this model's forced stamp with the other model's+ finetuning mode, drops to no mixed precision, and generation turns that back+ into the float16 the forced list exists to avoid.+ """+ env = {"UNSLOTH_FORCE_FLOAT32": "1", "UNSLOTH_ENABLE_FULL_FINETUNING": "1"}+ # A LoRA load between this model and its trainer.+ trainer = _build_trainer(+ env,+ torch.bfloat16,+ bf16_supported = True,+ full_finetuning = True,+ env_override = {"UNSLOTH_ENABLE_FULL_FINETUNING": "0"},+ )+ assert env["ACCELERATE_MIXED_PRECISION"] == "bf16"+ assert _generate(trainer, env, has_bf16 = True) == (True, torch.bfloat16)+++def test_an_unstamped_model_still_takes_the_environments_finetuning_mode():+ """The fallback, for a model loaded before this stamp existed."""+ env = {"UNSLOTH_FORCE_FLOAT32": "1", "UNSLOTH_ENABLE_FULL_FINETUNING": "1"}+ trainer = _build_trainer(env, torch.bfloat16, bf16_supported = True, mark_full_finetuning = False)+ assert not hasattr(trainer.model, "_unsloth_full_finetuning")+ assert env["ACCELERATE_MIXED_PRECISION"] == "bf16"+++def test_the_loaders_stamp_the_full_finetuning_answer_on_the_model():+ for rel in ("unsloth/models/loader.py", "unsloth/models/vision.py"):+ src = (REPO_ROOT / rel).read_text(encoding = "utf-8")+ assert "_mark_full_finetuning(" in src, rel+++def test_the_trainer_init_prefers_the_finetuning_stamp_over_the_shared_flag():+ """One fallback read, as with the forced float32 flag."""+ assert "_unsloth_full_finetuning" in MP_SRC+ reads = re.findall(r"environ\.get\(\s*['\"]UNSLOTH_ENABLE_FULL_FINETUNING", MP_SRC)+ assert len(reads) == 1, reads+++# ---- the same question again, inside native generation -------------------+++def _fast_generate_autocast_source() -> str:+ """The autocast unsloth_base_fast_generate builds around _old_generate."""+ src = (REPO_ROOT / "unsloth" / "models" / "vision.py").read_text(encoding = "utf-8")+ start = src.index(" # Mixed precision autocast")+ end = src.index(" # Prepare LoRA\n", start)+ return textwrap.dedent(src[start:end])+++class _RecordingTorch:+ """Real torch, except `autocast` records its arguments instead of applying them.++ `torch.autocast(device_type = "cuda", ...)` disables itself on a host with no+ CUDA, so reading `_enabled` off the constructed object measures the runner+ rather than the branch under test, and these tests could never pass on a+ CPU-only machine. What the code decides to ask for is the thing under test.+ """++ def __init__(self, calls):+ self._calls = calls++ def __getattr__(self, name):+ return getattr(torch, name)++ def autocast(+ self,+ device_type = None,+ dtype = None,+ enabled = True,+ **kwargs,+ ):+ self._calls.append((enabled, dtype))+ return nullcontext()+++def _fast_generate(model, env, dtype):+ """Build that autocast once and report what it would enter."""+ calls = []+ scope = {+ "torch": _RecordingTorch(calls),+ "os": types.SimpleNamespace(environ = env),+ "self": model,+ "dtype": dtype,+ "DEVICE_TYPE_TORCH": "cuda",+ }+ exec(_fast_generate_autocast_source(), scope)+ assert len(calls) == 1, calls+ enabled, fast_dtype = calls[0]+ return enabled, (fast_dtype if enabled else None)+++def test_a_forced_load_cannot_pull_generation_into_float16():+ """The trainer reads the stamp; native generation has to read it too.++ An explicitly float32, unforced model whose process later loads Gemma3 or+ gpt-oss gets UNSLOTH_FORCE_FLOAT32 = '1' written behind its back, and its+ rollouts would then run in the float16 autocast the trainer kept it out of.+ """+ model = types.SimpleNamespace(_unsloth_forced_float32 = False)+ env = {"UNSLOTH_FORCE_FLOAT32": "1"}+ assert _fast_generate(model, env, torch.float32) == (False, None)+++def test_a_forced_model_still_autocasts_after_a_plain_load():+ """The mirror: the stamp has to keep the float16 as well as refuse it."""+ model = types.SimpleNamespace(_unsloth_forced_float32 = True)+ env = {"UNSLOTH_FORCE_FLOAT32": "0"}+ assert _fast_generate(model, env, torch.float32) == (True, torch.float16)+++def test_generation_falls_back_to_the_environment_without_a_stamp():+ model = types.SimpleNamespace()+ assert _fast_generate(model, {"UNSLOTH_FORCE_FLOAT32": "1"}, torch.float32) == (+ True,+ torch.float16,+ )+ assert _fast_generate(model, {"UNSLOTH_FORCE_FLOAT32": "0"}, torch.float32) == (False, None)+++ "dtype, expected",+ [+ (torch.float16, (True, torch.float16)),+ (torch.bfloat16, (True, torch.bfloat16)),+ (torch.float32, (False, None)),+ ],+)+def test_generation_without_a_forced_family_is_unchanged(dtype, expected):+ model = types.SimpleNamespace(_unsloth_forced_float32 = False)+ assert _fast_generate(model, {}, dtype) == expected+++def test_the_loaders_stamp_the_forced_float32_answer_on_the_model():+ """The stamp has to exist for the trainer to read, on both loaders that+ consult the forced list."""+ for rel in ("unsloth/models/loader.py", "unsloth/models/vision.py"):+ src = (REPO_ROOT / rel).read_text(encoding = "utf-8")+ assert "_mark_forced_float32(" in src, rel+++def test_only_one_place_reads_the_shared_forced_float32_flag():+ """One fallback read, for models loaded before the stamp existed."""+ reads = re.findall(r"environ\.get\(\s*['\"]UNSLOTH_FORCE_FLOAT32", REPL_SRC)+ assert len(reads) == 1, reads+++def test_a_model_without_the_stamp_keeps_the_old_environment_answer():+ env = {"UNSLOTH_FORCE_FLOAT32": "1"}+ trainer = _build_trainer(env, torch.float32, bf16_supported = False, mark_forced_float32 = False)+ assert not hasattr(trainer.model, "_unsloth_forced_float32")+ assert _generate(trainer, env, has_bf16 = False) == (True, torch.float16)+++def test_a_forced_float32_load_cannot_force_an_unforced_trainer():+ """The mirror of the test above, for a model that was stamped.++ A float32 Llama on a T4 is not a forced family, and its loader never writes+ UNSLOTH_FORCE_FLOAT32, so loading Gemma3 or gpt-oss next sets '1' behind its+ back. Without the stamp on that model the first generation would read the+ other model's answer and turn float16 autocast back on.+ """+ env = {"UNSLOTH_FORCE_FLOAT32": "0"}+ trainer = _build_trainer(env, torch.float32, bf16_supported = False)+ assert trainer.model._unsloth_forced_float32 is False+ assert env["ACCELERATE_MIXED_PRECISION"] == "no"++ # A forced float32 family loaded before the first generation batch.+ env["UNSLOTH_FORCE_FLOAT32"] = "1"++ assert _generate(trainer, env, has_bf16 = False) == (False, None)+++ "model_dtype, bf16_supported, precision, autocast",+ [+ (torch.bfloat16, True, "bf16", (True, torch.bfloat16)),+ (torch.float16, False, "fp16", (True, torch.float16)),+ ],+)+def test_a_forced_load_earlier_in_the_process_cannot_force_this_trainer(+ model_dtype, bf16_supported, precision, autocast+):+ """The trainer's __init__ has to read the stamp too, not only generation.++ The legacy FastLanguageModel path never writes UNSLOTH_FORCE_FLOAT32, so a+ Gemma3 or gpt-oss loaded before it leaves '1' behind for a model that is not+ forced. Reading the env there drops the trainer to no mixed precision at all,+ and generation, which now reads the stamp, no longer puts the float16 back.+ A float16 model then trains with neither autocast nor a GradScaler.+ """+ env = {"UNSLOTH_FORCE_FLOAT32": "1"}+ trainer = _build_trainer(env, model_dtype, bf16_supported = bf16_supported, forced_float32 = False)+ assert env["ACCELERATE_MIXED_PRECISION"] == precision+ assert _generate(trainer, env, has_bf16 = bf16_supported) == autocast+++def test_an_unstamped_model_still_takes_the_environment_answer_in_init():+ """The fallback, for a model loaded before the stamp existed."""+ env = {"UNSLOTH_FORCE_FLOAT32": "1"}+ trainer = _build_trainer(env, torch.float32, bf16_supported = False, mark_forced_float32 = False)+ assert env["ACCELERATE_MIXED_PRECISION"] == "no"+ assert _generate(trainer, env, has_bf16 = False) == (True, torch.float16)+++def test_the_trainer_init_prefers_the_stamp_over_the_shared_flag():+ """One fallback read in the __init__ block, as in the generation helper."""+ assert "_unsloth_forced_float32" in MP_SRC+ reads = re.findall(r"environ\.get\(\s*['\"]UNSLOTH_FORCE_FLOAT32", MP_SRC)+ assert len(reads) == 1, reads+++def _own_returns(node):+ """Returns belonging to `node` itself, not to a function nested inside it."""+ found = []+ for child in ast.iter_child_nodes(node):+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):+ continue+ if isinstance(child, ast.Return) and child.value is not None:+ found.append(child)+ found.extend(_own_returns(child))+ return found+++def _exit_scopes(fn):+ """(scope, returns) for everything that hands a model back to the caller.++ `return _dispatch_diffusion()` exits through a local helper, so resolve one+ level of those: the helper is a scope of its own, and it has to answer for+ itself since the code after it never runs.+ """+ helpers = {n.name: n for n in ast.walk(fn) if isinstance(n, ast.FunctionDef) and n is not fn}+ own, scopes = [], []+ for ret in _own_returns(fn):+ call = ret.value+ if (+ isinstance(call, ast.Call)+ and isinstance(call.func, ast.Name)+ and call.func.id in helpers+ ):+ helper = helpers[call.func.id]+ scopes.append((helper, _own_returns(helper)))+ else:+ own.append(ret)+ if own:+ scopes.append((fn, own))+ return scopes+++def test_every_loader_return_path_stamps_the_forced_float32_answer():+ """Not just the paths that can answer True: a path that returns a model of+ its own has to say so either way, or the trainer falls back to the env.++ Includes the text-diffusion dispatch, which returns before the FORCE_FLOAT32+ scan, so nothing further down can answer for it."""+ seen = 0+ for rel in ("unsloth/models/loader.py", "unsloth/models/vision.py"):+ tree = ast.parse((REPO_ROOT / rel).read_text(encoding = "utf-8"))+ for node in ast.walk(tree):+ if not (isinstance(node, ast.FunctionDef) and node.name == "from_pretrained"):+ continue+ for scope, returns in _exit_scopes(node):+ calls = [+ (c.func.id, c.args[0].id)+ for c in ast.walk(scope)+ if isinstance(c, ast.Call)+ and isinstance(c.func, ast.Name)+ and c.func.id in ("_mark_requested_float32", "_mark_forced_float32")+ and c.args+ and isinstance(c.args[0], ast.Name)+ ]+ requested = {arg for name, arg in calls if name == "_mark_requested_float32"}+ forced = {arg for name, arg in calls if name == "_mark_forced_float32"}+ # `delegated` came from another from_pretrained, already stamped there.+ assert (requested - forced) <= {"delegated"}, (rel, requested, forced)+ for ret in returns:+ seen += 1+ statement = ast.unparse(ret)+ assert "_mark_requested_float32(" in statement, (rel, statement)+ assert seen >= 6, seen+++def test_the_diffusion_dispatch_stamps_both_answers():+ """A DiffusionGemma load leaves FastModel through _dispatch_diffusion, which+ predates this stamp: unstamped, a T4 float32 load autocasts to float16."""+ tree = ast.parse((REPO_ROOT / "unsloth/models/loader.py").read_text(encoding = "utf-8"))+ helper = next(+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.FunctionDef) and n.name == "_dispatch_diffusion"+ )+ body = ast.unparse(helper)+ assert "_mark_forced_float32(model, False)" in body+ assert "_mark_requested_float32(model, user_float32)" in body+++# ---- everything that must NOT change -------------------------------------+++def test_a_float16_trainer_alone_still_autocasts():+ env = {}+ trainer = _build_trainer(env, torch.float16, bf16_supported = False)+ assert env["ACCELERATE_MIXED_PRECISION"] == "fp16"+ assert _generate(trainer, env, has_bf16 = False) == (True, torch.float16)+++def test_a_bfloat16_trainer_alone_still_autocasts_in_bfloat16():+ env = {}+ trainer = _build_trainer(env, torch.bfloat16, bf16_supported = True)+ assert env["ACCELERATE_MIXED_PRECISION"] == "bf16"+ assert _generate(trainer, env, has_bf16 = True) == (True, torch.bfloat16)+++def test_pure_bfloat16_full_finetuning_still_does_not_autocast():+ env = {"UNSLOTH_MIXED_PRECISION": "bfloat16", "UNSLOTH_ENABLE_FULL_FINETUNING": "1"}+ trainer = _build_trainer(env, torch.bfloat16, bf16_supported = True)+ assert env["ACCELERATE_MIXED_PRECISION"] == "no"+ assert _generate(trainer, env, has_bf16 = True) == (False, None)+++def test_force_float32_still_autocasts_in_float16():+ """Gemma3 and gpt-oss set 'no' as well, and still want float16 autocast."""+ env = {"UNSLOTH_FORCE_FLOAT32": "1"}+ trainer = _build_trainer(env, torch.float32, bf16_supported = False)+ assert env["ACCELERATE_MIXED_PRECISION"] == "no"+ assert _generate(trainer, env, has_bf16 = False) == (True, torch.float16)+++def test_an_upcast_float32_trainer_still_gets_float16_autocast():+ """Only an explicit float32 load suppresses it, not the float32 that full+ finetuning upcasts to by itself (issue #4082)."""+ env = {"UNSLOTH_ENABLE_FULL_FINETUNING": "1"}+ trainer = _build_trainer(env, torch.float32, bf16_supported = False, user_float32 = False)+ assert env["ACCELERATE_MIXED_PRECISION"] == "fp16"+ assert _generate(trainer, env, has_bf16 = False) == (True, torch.float16)+++def test_a_trainer_rl_py_never_touched_falls_back_to_the_environment():+ """Nothing on args to read: an object with no fp16 / bf16 / mixed_precision+ must still get the old environment answer rather than silently 'no'."""+ env = {"ACCELERATE_MIXED_PRECISION": "fp16", "UNSLOTH_FORCE_FLOAT32": "0"}+ trainer = types.SimpleNamespace()+ assert _generate(trainer, env, has_bf16 = False) == (True, torch.float16)+++def test_only_one_place_reads_the_shared_environment():+ """One fallback read, in the helper that latches. Any other reader, in code+ or in an injected string, would be a way back to the process wide answer."""+ reads = re.findall(r"environ\.get\(\s*['\"]ACCELERATE_MIXED_PRECISION", REPL_SRC)+ assert len(reads) == 1, reads+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))+++def test_an_outer_autocast_is_inherited_rather_than_overridden():+ """Being inside an autocast must not crash, and must keep the outer dtype.++ The helper used to signal "do not name a dtype of my own" by setting+ `dtype = nullcontext()`. autocast passes whatever it is handed straight to+ `set_autocast_dtype`, which accepts a torch.dtype and nothing else, so that+ branch raised `TypeError: ... must be torch.dtype, not nullcontext` instead+ of doing nothing. The key has to be absent, not a sentinel.+ """+ if not torch.cuda.is_available():+ pytest.skip("needs CUDA: torch.is_autocast_enabled('cuda') is the branch")+ from unsloth.models.rl_replacements import _unsloth_grpo_autocast_kwargs++ class _Trainer:+ pass++ trainer = _Trainer()+ trainer._autocast_enabled = True+ trainer._autocast_dtype = torch.float16+ trainer._autocast_force_float32 = False++ # Outside: the helper names its own dtype.+ outside = _unsloth_grpo_autocast_kwargs(trainer)+ assert outside == {"enabled": True, "dtype": torch.float16}, outside++ # Inside: no dtype at all, and it must actually build an autocast.+ with torch.amp.autocast(device_type = "cuda", dtype = torch.bfloat16):+ inside = _unsloth_grpo_autocast_kwargs(trainer)+ assert "dtype" not in inside, inside+ with torch.amp.autocast(device_type = "cuda", **inside):+ x = torch.randn(4, 4, device = "cuda")+ assert (x @ x).dtype is torch.bfloat16++ # Forcing float32 keeps naming float16 even inside an outer autocast.+ trainer._autocast_force_float32 = True+ with torch.amp.autocast(device_type = "cuda", dtype = torch.bfloat16):+ forced = _unsloth_grpo_autocast_kwargs(trainer)+ assert forced == {"enabled": True, "dtype": torch.float16}, forced+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))diff --git a/tests/test_missing_optional_dep_skips.py b/tests/test_missing_optional_dep_skips.pyindex 074797161c9..94e14ea7f65 100644--- a/tests/test_missing_optional_dep_skips.py+++ b/tests/test_missing_optional_dep_skips.py@@ -7,10 +7,12 @@ import textwrapimport pytest-from tests.utils.os_utils import require_python_package+from tests.utils.os_utils import require_package, require_python_package_ABSENT = "unsloth_definitely_not_a_real_package_xyz"+_ABSENT_SYSTEM = "unsloth-nonexistent-system-package"+_ABSENT_EXECUTABLE = "unsloth-nonexistent-executable"def _repo_root():@@ -23,8 +25,51 @@ def test_a_missing_package_skips_the_module_under_pytest():require_python_package(_ABSENT)+def test_a_missing_system_package_skips_the_module_too():+ with pytest.raises(pytest.skip.Exception):+ require_package(_ABSENT_SYSTEM, _ABSENT_EXECUTABLE)++def test_an_installed_package_is_a_no_op():require_python_package("sys", import_name = "sys")+ require_package("python", sys.executable)+++ "helper, args",+ [+ ("require_package", f"{_ABSENT_SYSTEM!r}, {_ABSENT_EXECUTABLE!r}"),+ ("require_python_package", f"{_ABSENT!r}"),+ ],+)+def test_the_call_at_module_scope_does_not_kill_the_session(tmp_path, helper, args):+ """The real regression: the helper at import time, in its own pytest session."""+ module = tmp_path / f"test_absent_{helper}.py"+ module.write_text(+ textwrap.dedent(f"""+ import sys+ sys.path.insert(0, {str(_repo_root())!r})+ from tests.utils.os_utils import {helper}+ {helper}({args})++ def test_unreachable():+ raise AssertionError("the module-level skip should have stopped this")+ """),+ encoding = "utf-8",+ )++ result = subprocess.run(+ [sys.executable, "-m", "pytest", str(module), "-q", "-p", "no:cacheprovider"],+ capture_output = True,+ text = True,+ cwd = str(tmp_path),+ )+ output = result.stdout + result.stderr+ assert "INTERNALERROR" not in output, output+ assert "SystemExit" not in output, output+ assert "skipped" in output, output+ # 5 is "no tests ran", which a module-level skip legitimately produces.+ assert result.returncode in (0, 5), f"exit code {result.returncode}\n{output}"def test_the_standalone_script_path_still_exits():diff --git a/tests/utils/os_utils.py b/tests/utils/os_utils.pyindex cafb313bc40..ea419148c77 100644--- a/tests/utils/os_utils.py+++ b/tests/utils/os_utils.py@@ -6,11 +6,13 @@ import importlibdef _missing_dependency(message):- """Skip under pytest, since exiting at import time aborts the whole session."""+ """Skip under pytest, since exiting at import time aborts the whole session.++ Returns under a plain script so the caller can still print its install+ guidance before exiting; skipping first keeps that out of a test run."""if "pytest" in sys.modules:import pytestpytest.skip(message, allow_module_level = True)- sys.exit(1)TRUTHY = ("1", "true", "yes", "on")@@ -99,6 +101,8 @@ def require_package(package_name, executable_name = None):print(f"β Package {package_name} is installed")return+ _missing_dependency(f"requires the system package '{package_name}'")+print(f"β Error: {package_name} is not installed")print(f"\nPlease install {package_name} using your system package manager:")@@ -120,7 +124,7 @@ def require_package(package_name, executable_name = None):print(f" conda install -c conda-forge {package_name}")print(f"\nPlease install the required package and run the script again.")- _missing_dependency(f"{package_name} is not installed")+ sys.exit(1)# Usage@@ -139,12 +143,14 @@ def require_python_package(pip_name = package_nameif importlib.util.find_spec(import_name) is None:+ _missing_dependency(f"requires the '{package_name}' package (pip install {pip_name})")+print(f"β Error: Python package '{package_name}' is not installed")print(f"\nPlease install {package_name} using pip:")print(f" pip install {pip_name}")print(f" # or with conda:")print(f" conda install {pip_name}")print(f"\nAfter installation, run this script again.")- _missing_dependency(f"Python package '{package_name}' is not installed")+ sys.exit(1)else:print(f"β Python package '{package_name}' is installed")diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 7d67356d891..19b598cf24a 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -17,6 +17,10 @@ __version__ = "2026.8.9"__all__ = ["SUPPORTS_BFLOAT16","is_bfloat16_supported",+ "_requested_float32",+ "_mark_requested_float32",+ "_mark_forced_float32",+ "_mark_full_finetuning","is_vLLM_available","prepare_model_for_kbit_training","xformers",@@ -1995,7 +1999,7 @@ for model_name in model_architectures:breakconfig_filepath = f"transformers.models.{model_name}.configuration_{model_name}"model_filepath = f"transformers.models.{model_name}.modeling_{model_name}"- config_filename = f"{model_name.title().replace('_','')}Config" # qwen3 arch folder is qwen3_moe but config is Qwen3Config. Need to remove underscore(_) for now+ config_filename = f"{model_name.title().replace('_', '')}Config" # qwen3 arch folder is qwen3_moe but config is Qwen3Config. Need to remove underscore(_) for nowtry:exec(f"from {config_filepath} import {config_filename}", globals())except:@@ -2148,7 +2152,7 @@ if DEVICE_TYPE == "cuda":import transformers.utils.import_utilstransformers.utils.import_utils.is_flash_attn_2_available = (- lambda *args, **kwargs: False+ lambda *args, **kwargs: (False))import transformers.utils@@ -2192,8 +2196,8 @@ elif DEVICE_TYPE == "hip":# Stop Flash Attention from importing!import transformers.utils.import_utils- transformers.utils.import_utils.is_flash_attn_2_available = (- lambda *args, **kwargs: False+ transformers.utils.import_utils.is_flash_attn_2_available = lambda *args, **kwargs: (+ False)import transformers.utils@@ -2823,6 +2827,53 @@ def is_bfloat16_supported():return SUPPORTS_BFLOAT16+def _requested_float32(dtype):+ """Did the caller ask for float32, or did we arrive at it?++ Reads `dtype` as given: it is also derived from a 4bit config's+ `bnb_4bit_compute_dtype`, which describes one matmul and not the model.+ """+ if isinstance(dtype, str):+ dtype = getattr(torch, dtype, None)+ return dtype is torch.float32+++def _mark_requested_float32(model, requested):+ """Record on the model, not in the environment: with two models loaded before+ a trainer is built, an env var describes whichever loaded last. Outermost+ caller wins, since only it saw dtype before normalization.+ """+ try:+ model._unsloth_user_float32 = bool(requested)+ except Exception:+ pass+ return model+++def _mark_forced_float32(model, forced):+ """Record whether this model's family forced float32. UNSLOTH_FORCE_FLOAT32+ says the same, but every load rewrites it, so a second load before this model+ trains would answer for the wrong model.+ """+ try:+ model._unsloth_forced_float32 = bool(forced)+ except Exception:+ pass+ return model+++def _mark_full_finetuning(model, full_finetuning):+ """Record how this model was loaded. UNSLOTH_ENABLE_FULL_FINETUNING is process+ wide and every load rewrites it, so a LoRA model loaded before this one trains+ would answer "no" here and cost it the bfloat16 full finetuning may keep.+ """+ try:+ model._unsloth_full_finetuning = bool(full_finetuning)+ except Exception:+ pass+ return model++def is_vLLM_available():return _package_available("vllm")@@ -3949,8 +4000,8 @@ def _prepare_model_for_qat(weight_dtype = torch.int8,granularity = PerGroup(group_size),)- filter_fn = (- lambda m, _: isinstance(m, torch.nn.Linear)+ filter_fn = lambda m, _: (+ isinstance(m, torch.nn.Linear)and m.in_features >= group_sizeand m.in_features % group_size == 0)diff --git a/unsloth/models/loader.py b/unsloth/models/loader.pyindex d414ad76f84..38eeb6e7e53 100644--- a/unsloth/models/loader.py+++ b/unsloth/models/loader.py@@ -105,6 +105,10 @@ from ._utils import (process_vision_info,unsloth_compile_transformers,fast_inference_setup,+ _requested_float32,+ _mark_requested_float32,+ _mark_forced_float32,+ _mark_full_finetuning,_get_text_only_config,resolve_model_class,_is_family_text_decoder,@@ -452,6 +456,9 @@ class FastLanguageModel(FastLlamaModel):load_in_4bit = False# Login to allow private models+ # Before normalization: dtype is also derived below from a 4bit config's+ # compute dtype, which is not a request for the whole model.+ user_float32 = _requested_float32(dtype)token = hf_login(token)# Align dtype with bnb_4bit_compute_dtype if provided and dtype is unset.if dtype is None and quantization_config is not None:@@ -478,7 +485,7 @@ class FastLanguageModel(FastLlamaModel):# @_offline_aware_load already forced offline when needed; delegations inherit it.if load_in_8bit or full_finetuning or qat_scheme is not None:- return FastModel.from_pretrained(+ delegated, tokenizer = FastModel.from_pretrained(model_name = model_name,max_seq_length = max_seq_length,dtype = dtype,@@ -513,6 +520,7 @@ class FastLanguageModel(FastLlamaModel):*args,**kwargs,)+ return _mark_requested_float32(delegated, user_float32), tokenizerif isinstance(dtype, str) and dtype in ["float16", "bfloat16"]:dtype = getattr(torch, dtype)@@ -896,7 +904,7 @@ class FastLanguageModel(FastLlamaModel):# elif model_type == "granite":# dispatch_model = FastGraniteModelelse:- return FastModel.from_pretrained(+ delegated, tokenizer = FastModel.from_pretrained(model_name = old_model_name,max_seq_length = max_seq_length,dtype = dtype,@@ -931,6 +939,7 @@ class FastLanguageModel(FastLlamaModel):*args,**kwargs,)+ return _mark_requested_float32(delegated, user_float32), tokenizer# Apply gradient checkpointing with smart heuristicsuse_gradient_checkpointing = apply_unsloth_gradient_checkpointing(@@ -1103,7 +1112,12 @@ class FastLanguageModel(FastLlamaModel):model = _fix_rope_inv_freq(model)model = _exclude_rope_inv_freq_from_ddp(model)- return model, tokenizer+ # This path never sets UNSLOTH_FORCE_FLOAT32, so answer False rather than+ # leave the trainer reading whatever a later load writes to the environment.+ model = _mark_forced_float32(model, False)+ # Full finetuning delegates to FastModel above, so this path is always LoRA.+ model = _mark_full_finetuning(model, False)+ return _mark_requested_float32(model, user_float32), tokenizerfrom ..kernels import (@@ -1208,6 +1222,9 @@ class FastModel(FastBaseModel):load_in_4bit = False# Login to allow private models+ # Before normalization: dtype is also derived below from a 4bit config's+ # compute dtype, which is not a request for the whole model.+ user_float32 = _requested_float32(dtype)token = hf_login(token)if whisper_language is not None:assert type(whisper_language) is str@@ -1426,7 +1443,7 @@ class FastModel(FastBaseModel):# Text-diffusion slow-path dispatch, factored so both the normal route (below) and the# legacy-config fallback (in the AutoConfig except handler) share one call site.def _dispatch_diffusion():- return FastDiffusionModel.from_pretrained(+ model, tokenizer = FastDiffusionModel.from_pretrained(model_name = model_name,max_seq_length = max_seq_length,dtype = dtype,@@ -1440,6 +1457,12 @@ class FastModel(FastBaseModel):revision = base_revision,**kwargs,)+ # Returns before the FORCE_FLOAT32 scan and no diffusion type is on that+ # list, so False. Stamped, not left unset, or the trainer reads whatever+ # UNSLOTH_FORCE_FLOAT32 an earlier load wrote.+ model = _mark_forced_float32(model, False)+ model = _mark_full_finetuning(model, full_finetuning)+ return _mark_requested_float32(model, user_float32), tokenizertry:model_config = user_config@@ -1793,6 +1816,7 @@ class FastModel(FastBaseModel):or disable_name.lower() in model_types_all) and ((dtype == torch.float16) or not SUPPORTS_BFLOAT16):os.environ["UNSLOTH_FORCE_FLOAT32"] = "1"+ do_forced_float32 = Truedtype = torch.bfloat16 # Change to bfloat16 loadingbreak# Apply gradient checkpointing with smart heuristics@@ -2148,7 +2172,9 @@ class FastModel(FastBaseModel):model = _fix_rope_inv_freq(model)model = _exclude_rope_inv_freq_from_ddp(model)- return model, tokenizer+ model = _mark_forced_float32(model, do_forced_float32)+ model = _mark_full_finetuning(model, full_finetuning)+ return _mark_requested_float32(model, user_float32), tokenizerclass FastVisionModel(FastModel):diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex 458f96216b4..b6c94d6efc8 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -1978,8 +1978,15 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):# bf16 (V100/T4) keep them in float32 so they never autocast to fp16. On a bf16 GPU,# full finetuning can still use bf16 autocast (master weights stay float32), which is# faster and uses less memory; LoRA/QLoRA keep float32 when forced.- "full_finetuning = os.environ.get('UNSLOTH_ENABLE_FULL_FINETUNING', '0') == '1'\n"- "if os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '1' and not (full_finetuning and _bf16_supported()):\n"+ # Stamped by from_pretrained: the env is process wide, so a LoRA model+ # loaded after this one would cost this trainer its bfloat16.+ "full_finetuning = getattr(model, '_unsloth_full_finetuning', None)\n"+ "if full_finetuning is None: full_finetuning = os.environ.get('UNSLOTH_ENABLE_FULL_FINETUNING', '0') == '1'\n"+ # Stamped by from_pretrained: the env is process wide, so a forced family+ # loaded earlier would answer here for a model that is not forced at all.+ "model_forced_float32 = getattr(model, '_unsloth_forced_float32', None)\n"+ "if model_forced_float32 is None: model_forced_float32 = os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '1'\n"+ "if model_forced_float32 and not (full_finetuning and _bf16_supported()):\n"" print('Unsloth: Switching to float32 training since model cannot work with float16')\n"" force_float32 = True\n""mixed_precision_dtype = os.environ.get('UNSLOTH_MIXED_PRECISION', 'float32')\n"@@ -1989,6 +1996,10 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):"dtype = _get_dtype(dtype)\n""float16 = dtype == torch.float16\n""bfloat16 = dtype == torch.bfloat16\n"+ "float32 = dtype == torch.float32\n"+ # Set only when the caller passed dtype = torch.float32 themselves: a+ # request, not a side effect of upcasting, and immune to a second load.+ "user_float32 = bool(getattr(model, '_unsloth_user_float32', False))\n""if full_finetuning:\n"" if bfloat16 and use_fp16: use_fp16 = False\n"" if float16 and use_bf16: use_bf16 = False\n"@@ -2001,6 +2012,16 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):" os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'\n"" if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'\n"" # args.mixed_precision is a new argument which needs to be set now\n"+ "elif (not use_bf16 and not use_fp16) and mixed_precision_dtype == 'float32' and float32 and user_float32 and not _bf16_supported():\n"+ # Without bf16 the only autocast is float16, whose narrower exponent range+ # overflows float32 values to inf then NaN. Gated on the explicit request:+ # full finetuning upcasts to float32 itself, and float16 autocast over+ # float32 master weights is the normal V100/T4 recipe (see #4082).+ " print('Unsloth: Model is in float32 and this GPU has no bfloat16 support, so training stays in float32. Pass fp16 = True to force float16 mixed precision instead.')\n"+ " args.fp16 = False\n"+ " args.bf16 = False\n"+ " os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'\n"+ " if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'\n""elif (not use_bf16 and not use_fp16) and mixed_precision_dtype == 'float32':\n"" # Mixed precision training. bf16 only if the GPU supports it; V100/T4 use fp16.\n"" use_bf16_amp = (not float16) and _bf16_supported()\n"diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex e48ff0dbe1d..c6355a14cb3 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -945,18 +945,66 @@ RL_FUNCTIONS["sft_trainer"].append(sft_trainer_push_to_hub_token)# Autocast precision for GRPO+def _unsloth_grpo_autocast(self):+ """Decide the GRPO autocast once and latch it on the trainer.++ ACCELERATE_MIXED_PRECISION is process wide, so a trainer built later but run+ first would hand this trainer its precision. args belongs to this trainer.+ """+ if not hasattr(self, "_autocast_enabled"):+ args = getattr(self, "args", None)+ precision = getattr(args, "mixed_precision", None)+ use_bf16 = getattr(args, "bf16", None)+ use_fp16 = getattr(args, "fp16", None)+ if not isinstance(precision, str):+ # transformers < 5 has no args.mixed_precision, but rl.py sets the+ # fp16 / bf16 flags on this same args for every branch it takes.+ if isinstance(use_bf16, bool) and isinstance(use_fp16, bool):+ precision = "bf16" if use_bf16 else ("fp16" if use_fp16 else "no")+ else:+ precision = os.environ.get("ACCELERATE_MIXED_PRECISION", "fp16")+ self._autocast_dtype = torch.float16 if precision == "fp16" else torch.bfloat16+ # "no" is a real value: full finetuning and an explicit float32 load+ # both set it, and reading it as bfloat16 raises on a T4 or V100.+ self._autocast_enabled = precision != "no"+ self._autocast_force_float32 = False+ # Stamped by from_pretrained: UNSLOTH_FORCE_FLOAT32 is process wide, so a+ # model loaded after this trainer was built would answer for it here.+ forced = getattr(getattr(self, "model", None), "_unsloth_forced_float32", None)+ if forced is None:+ forced = os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1"+ if forced and precision != "bf16":+ # Gemma3 / gpt-oss set "no" but still want float16 autocast. A trainer+ # already on bf16 keeps it: float16 is what the forced list avoids.+ self._autocast_dtype = torch.float16+ self._autocast_enabled = True+ self._autocast_force_float32 = True++ return self._autocast_enabled, self._autocast_dtype+++def _unsloth_grpo_autocast_kwargs(self, device_type = "cuda"):+ """torch.amp.autocast kwargs for GRPO generation."""+ enabled, dtype = _unsloth_grpo_autocast(self)+ if not getattr(self, "_autocast_force_float32", False) and torch.is_autocast_enabled(+ device_type+ ):+ # Already inside an autocast: inherit its dtype by omitting the key, since+ # autocast passes whatever it gets straight to set_autocast_dtype.+ return {"enabled": enabled}+ return {"enabled": enabled, "dtype": dtype}++def grpo_trainer__prepare_inputs(function_name, function):if function_name != "_prepare_inputs":return function- # Add mixed precision training+ # Latched on the trainer, so a second trainer's __init__ cannot change this+ # trainer's autocast mid run.function = function.replace("with torch.inference_mode():","with torch.inference_mode(), "- "torch.amp.autocast(device_type = 'cuda', "- "dtype = ((torch.float16 if os.environ.get('ACCELERATE_MIXED_PRECISION', 'fp16') == 'fp16' else torch.bfloat16) "- "if not torch.is_autocast_enabled('cuda') else nullcontext())"- "if os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '0' else torch.float16):",+ "torch.amp.autocast(device_type = 'cuda', **_unsloth_grpo_autocast_kwargs(self)):",)function = function.replace("self.accelerator.unwrap_model(self.model)",@@ -1426,17 +1474,14 @@ def grpo_trainer__get_per_token_logps(function_name, function):if True: # os.environ.get('UNSLOTH_USE_NEW_MODEL', '0') == '0':return None # Unsloth efficient GRPO# Otherwise, calculate normally:- if not hasattr(self, "_autocast_dtype"):- self._autocast_dtype = (- torch.float16- if os.environ.get("ACCELERATE_MIXED_PRECISION", "fp16") == "fp16"- else torch.bfloat16- )- if os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1":- self._autocast_dtype = torch.float16+ _unsloth_grpo_autocast(self)os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1"- with torch.amp.autocast(device_type = DEVICE_TYPE, dtype = self._autocast_dtype):+ with torch.amp.autocast(+ device_type = DEVICE_TYPE,+ dtype = self._autocast_dtype,+ enabled = getattr(self, "_autocast_enabled", True),+ ):# We add 1 to `logits_to_keep` because the last logits of the sequence is later excludedlogits = model(input_ids = input_ids,@@ -1492,14 +1537,7 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):if compute_efficient:return None, Noneelse:- if not hasattr(self, "_autocast_dtype"):- self._autocast_dtype = (- torch.float16- if os.environ.get("ACCELERATE_MIXED_PRECISION", "fp16") == "fp16"- else torch.bfloat16- )- if os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1":- self._autocast_dtype = torch.float16+ _unsloth_grpo_autocast(self)compute_aux_loss = kwargs.get("compute_aux_loss", None)@@ -1524,7 +1562,12 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):lm_head = self.model.get_output_embeddings().weight- dtype_bytes = 16 if self._autocast_dtype in [torch.float16, torch.bfloat16] else 32+ # Size on the dtype the forward actually runs in: with autocast off that+ # is the model's own dtype, float32 or bfloat16 depending on the load.+ forward_dtype = (+ self._autocast_dtype if getattr(self, "_autocast_enabled", True) else lm_head.dtype+ )+ dtype_bytes = 16 if forward_dtype in [torch.float16, torch.bfloat16] else 32total_rows = input_ids.shape[0]seq_len = input_ids.shape[1]hidden_dim = lm_head.shape[1]@@ -1790,7 +1833,9 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):def _pg_run_forward(_pg_layout = _pg_layout, _pg_chunks = _pg_chunks):with _get_inference_mode_context_manager(model):with torch.amp.autocast(- device_type = "cuda", dtype = self._autocast_dtype+ device_type = "cuda",+ dtype = self._autocast_dtype,+ enabled = getattr(self, "_autocast_enabled", True),):_pg_hidden = unwrapped_model(input_ids = _pg_layout.flat_ids,@@ -1921,7 +1966,11 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):_pk_cstart = (_pk_L - logits_to_keep) - left_pad_tokens_per_prompt # [rows]_pk_ctgt = (_pk_nz_idx[1:, 1] >= _pk_cstart[_pk_nz_idx[1:, 0]]) & _pk_withinwith _get_inference_mode_context_manager(model):- with torch.amp.autocast(device_type = "cuda", dtype = self._autocast_dtype):+ with torch.amp.autocast(+ device_type = "cuda",+ dtype = self._autocast_dtype,+ enabled = getattr(self, "_autocast_enabled", True),+ ):# use_cache=False: a KV cache silently disables varlen packing_pk_hidden = unwrapped_model(input_ids = _pk_flat,@@ -1970,7 +2019,9 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):_pk_ref = torch.zeros_like(_pk_result)with _get_inference_mode_context_manager(model):with torch.amp.autocast(- device_type = "cuda", dtype = self._autocast_dtype+ device_type = "cuda",+ dtype = self._autocast_dtype,+ enabled = getattr(self, "_autocast_enabled", True),):for _pk_i in range(total_rows):_pk_ni = _pk_len_cpu[_pk_i]@@ -2144,7 +2195,11 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):_extra_vision_kwargs["token_type_ids"] = token_type_ids_chunkif mm_token_type_ids_chunk is not None:_extra_vision_kwargs["mm_token_type_ids"] = mm_token_type_ids_chunk- with torch.amp.autocast(device_type = "cuda", dtype = self._autocast_dtype):+ with torch.amp.autocast(+ device_type = "cuda",+ dtype = self._autocast_dtype,+ enabled = getattr(self, "_autocast_enabled", True),+ ):if pixel_values is None:outputs = unwrapped_model(input_ids = input_ids_chunk,@@ -2310,6 +2365,8 @@ grpo_compute_loss_slow = RL_REPLACEMENTS["grpo_compute_loss_slow"]UnslothEfficientGRPO = RL_REPLACEMENTS["UnslothEfficientGRPO"]grpo_accumulated_loss = RL_REPLACEMENTS["grpo_accumulated_loss"]grpo_update_SamplingParams = RL_REPLACEMENTS["grpo_update_SamplingParams"]+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast))+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast_kwargs))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_model_config))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_final_logit_softcapping))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_mm_token_id))diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 710ffe6c4bb..2fb915cdd2c 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -589,8 +589,12 @@ def unsloth_base_fast_generate(self, *args, **kwargs):except:pass- # Mixed precision autocast- if os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1":+ # Mixed precision autocast. Stamped by from_pretrained: UNSLOTH_FORCE_FLOAT32 is+ # process wide, so a later load would otherwise decide this model's rollouts.+ forced_float32 = getattr(self, "_unsloth_forced_float32", None)+ if forced_float32 is None:+ forced_float32 = os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1"+ if forced_float32:autocaster = torch.autocast(device_type = DEVICE_TYPE_TORCH, dtype = torch.float16)dtype = torch.float16else:@@ -1045,6 +1049,9 @@ class FastBaseModel:# The base + tokenizer prefetch runs AFTER the load-mode validation below, so an invalid# load_in_* combination fails without first downloading a snapshot.+ # Whether float32 was asked for rather than arrived at by upcasting. Only an+ # explicit request may suppress the V100/T4 float16 autocast (see #4082).+ user_float32 = _requested_float32(dtype)if dtype is None:dtype = torch.float16 if not SUPPORTS_BFLOAT16 else torch.bfloat16elif os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1":@@ -1230,6 +1237,8 @@ class FastBaseModel:"use `float32_mixed_precision = False` during FastLanguageModel.from_pretrained")os.environ["UNSLOTH_BFLOAT16_MIXED_PRECISION"] = "1"+ elif dtype == torch.float32:+ print("Unsloth: Using float32 full finetuning.")else:print("Unsloth: Float16 full finetuning uses more memory since we upcast weights to float32."@@ -1821,7 +1830,9 @@ class FastBaseModel:# Saving restores sentencepiece assets from the repo name alone, which carries no# branch. Stamped here, not per processor branch, so a fallback cannot lose it._mark_loaded_revision(tokenizer, _tokenizer_revision)- return model, tokenizer+ model = _mark_forced_float32(model, do_forced_float32)+ model = _mark_full_finetuning(model, full_finetuning)+ return _mark_requested_float32(model, user_float32), tokenizer@staticmethoddef get_peft_model(