Repository navigation
Keep an explicitly requested float32 model in float32 without bfloat16 - #7867
Conversation
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…or PR unslothai#7867 require_package exited the process when a system package was absent. The TTS test modules call it at import time, so under pytest the SystemExit escaped collection and ended the run with INTERNALERROR / exit code 3 instead of skipping one file. It now degrades to a module-level skip under pytest, the same treatment require_python_package already had, and keeps the exit for the standalone script callers. test_whisper.py also imported the unsloth runtime unguarded, which is a collection error on the Windows runner where triton is absent; guard it with a module-level skip.
The merge left this branch's _skip_if_pytest alongside main's _missing_dependency, doing the same job, plus two near-duplicate test files. Fold both into main's helper and its test module, keeping this branch's extra coverage of require_package and of the call at module scope.
torch.autocast(device_type = 'cuda') disables itself when CUDA is absent, so reading _enabled off the constructed object measured the runner instead of the branch, and these could never pass on a CPU-only machine, a Mac or Windows. Record the arguments the code asks for instead. Also skip before importing rl_replacements, which needs unsloth_zoo.
The ruff-format-with-kwargs hook installs ruff==0.6.9 through additional_dependencies, and 0.6.9 and 0.15 disagree on where the message goes in a multi-line assert and on how a long lambda signature wraps. I had run the script with the workspace ruff, so pre-commit.ci kept reformatting these back and failing, with nothing to show in the diff. AST is identical on all three.
9128efd to
6a0dcc3
Compare
Left over from the earlier shape of the autocast gating, which now omits dtype instead of passing a sentinel context. Source lint's import-hoist check treats an added-but-unused hoisted import as a blocker, and it is right: nothing in this file references it.
|
Pushed The check is right. Verifier on the new head: The two Every other check was already green, including Core on HF=4.57.6 + TRL<1, HF=default and HF=latest + TRL=latest, Repo tests (CPU) on Python 3.10 through 3.13, and the Windows install and VC++ round-trip jobs. Not re-triggering a review, since Codex had already answered with nothing left to triage and this was purely the lint gate. |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Validated on hardware.
That row was one of the four CONFIRMED_REGRESSION notebooks in the sweep against main, and this is what clears it. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7864a102ae
ℹ️ 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".
| # from_pretrained stamps this on the model it loaded. UNSLOTH_FORCE_FLOAT32 | ||
| # is process wide and every load rewrites it, so a model loaded after this | ||
| # trainer was built would otherwise answer for it here. | ||
| forced = getattr(getattr(self, "model", None), "_unsloth_forced_float32", None) |
There was a problem hiding this comment.
Unwrap the model before reading its precision stamp
When distributed training wraps self.model in DDP/Accelerate, the wrapper does not expose arbitrary attributes stored on its inner module, so this lookup returns None and falls back to the process-wide environment. For example, if an explicit-float32 trainer is created first and a forced-float32 model is loaded afterward, starting the first trainer under DDP reads the later model's UNSLOTH_FORCE_FLOAT32=1 and re-enables float16 autocast, recreating the T4/V100 overflow this change is meant to prevent. Read the stamp from the unwrapped model (including .module) before using the environment fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not correct: self.model is never the DDP wrapper. Checked the transformers source rather than reasoning from the wrapper's behaviour. In _inner_training_loop the prepared model is bound to self.model_wrapped only (if model is not self.model: self.model_wrapped = model), and the comment right below it states self.model is the Transformers Model except when we are using FSDP (4.57.6 trainer.py:2490-2494, and the same two lines on main at 1637/2689). So under DDP, DeepSpeed or DataParallel this lookup reads the bare PreTrainedModel that from_pretrained stamped.
FSDP is the one case where self.model is reassigned to a wrapper, and there the stamp still resolves: FullyShardedDataParallel.__getattr__ forwards missing attributes to _fsdp_wrapped_module (torch fully_sharded_data_parallel.py:530-535). FSDP2 mutates the module in place, so there is no wrapper at all. Nothing in unsloth or TRL rebinds self.model either, so there is no path where the environment fallback is reached on a stamped model.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
#7867) * Keep an explicitly requested float32 model in float32 without bfloat16 A model loaded with dtype = torch.float32 was being wrapped in float16 autocast on V100/T4 even when the caller set fp16 = False and bf16 = False. The mixed precision block in rl.py reads "neither flag set" as "caller did not choose" and picks for them: use_bf16_amp = (not float16) and _bf16_supported() args.fp16 = not use_bf16_amp so on a GPU without bf16 the answer is always float16. float16 has five exponent bits against float32's eight, so a value the model was loaded wide enough to hold overflows to inf and then NaN. Spark_TTS_(0_5B) is the case that surfaced it: it loads with dtype = torch.float32 ("Spark seems to only work on float32 for now"), sets fp16 = False, bf16 = False, and on a T4 logs nan for every step, then dies at inference inside torch.multinomial, which refuses a distribution containing NaN. The sampler assert is two steps downstream of the cause. Suppressing the autocast for every float32 model is too wide: full finetuning upcasts trainable weights to float32 by itself, and float16 autocast over float32 master weights is the ordinary V100/T4 recipe (issue #4082, tests/python/test_v100_fullft_precision.py). So from_pretrained now records whether float32 was ASKED for in UNSLOTH_USER_FLOAT32, as opposed to arrived at by upcasting, and only an explicit request suppresses the autocast. It is set in both loaders, since FastLanguageModel and FastBaseModel resolve dtype independently, and written on every load so a previous run cannot leave a stale "1" behind. Only the float16 fallback changes. bf16 has float32's exponent range, so a bf16 GPU keeps autocasting and keeps the memory saving. An explicit fp16 = True or bf16 = True is still obeyed, float16 and bfloat16 models are untouched, and UNSLOTH_FORCE_FLOAT32 models still take their earlier branch. tests/test_float32_no_fp16_autocast.py pulls the mixed precision block out of rl.py by AST and executes it against fake args/model objects with the bf16 capability check stubbed, so the no-bf16 path is covered without a V100/T4. No GPU, no network, no trl import. Also, separately: do not let one optional audio dependency kill the whole test session. require_python_package calls sys.exit(1) when a package is missing, and every caller is a test module invoking it at import time, so under pytest that is not a skip of one module -- SystemExit propagates out of collection and the run ends with INTERNALERROR> SystemExit: 1 with no report at all. A missing xcodec2 took out 1000+ unrelated tests. It now skips the module under pytest; outside pytest the exit is unchanged, since these helpers are also used by standalone scripts. test_whisper.py had the same shape for a different reason: it downloads an audio fixture at import and did `assert False` on failure. Wikimedia rate limits and this URL really did answer 429 during a batch run, and an asset we could not fetch says nothing about unsloth, so it skips too. * Record the float32 request on the model, and let GRPO honour a disabled autocast Two real gaps in the float32 gating, plus the provenance problem underneath both. The gate never reached most users. llama, mistral, gemma, gemma2, qwen2 and qwen3 LoRA/QLoRA loads go through FastLanguageModel to dispatch_model.from_pretrained, which is neither of the two loaders that recorded the request, so user_float32 stayed false and the fp16 autocast this branch exists to avoid ran anyway. That is most of the notebooks. The value was also process-global and derived rather than asked for. A program that loads two models before building a trainer described whichever loaded last, and a dtype inferred from a 4bit config's bnb_4bit_compute_dtype was recorded as an explicit model-wide request, which is especially wrong under full finetuning where the loader then turns 4bit off again. Both entry points now read the argument as the caller wrote it, before any normalisation, and the answer is attached to the model. The outermost caller wins, since only it saw the raw argument; the two delegating returns in FastLanguageModel re-stamp it for that reason. Then ACCELERATE_MIXED_PRECISION = 'no' was read as a two-way switch in the GRPO replacements, so 'no' came out as bfloat16 and autocast was entered anyway. torch does not ignore that on a T4 or V100, it raises "Current CUDA Device does not support bfloat16", which is exactly the hardware this branch targets. Verified against torch's own autocast __init__: the check is gated on `enabled`, so disabling autocast is both the correct reading of 'no' and the minimal fix. Full finetuning already set 'no', so this was reachable before this PR too. Tests: 4384 passed against 4369 on the same tree with these changes stashed, identical 1310 environment failures either way, and nothing failing on this branch that is not also failing on its base. * Keep forced float32 on fp16 autocast, size GRPO chunks by the flag, and run the tests off a GPU Three follow-ups on the autocast change. UNSLOTH_FORCE_FLOAT32 exports ACCELERATE_MIXED_PRECISION 'no' as well, and the new gate read only that, so the injected _prepare_inputs header disabled autocast for it while the dtype expression right beside it was still choosing float16. That left Gemma3 and gpt-oss generation in full float32, and it disagreed with the two other consumers, which set _autocast_enabled True for exactly this case. The header honours the flag now. The GRPO chunk autotuner derived dtype_bytes from _autocast_dtype alone, which stays bfloat16 when autocast is off, so it sized hidden states and logits as 16-bit for a forward running in float32. That is half the real figure, on the explicit-float32 and full-finetuning runs this branch is for. The new tests drove torch.amp.autocast(device_type = "cuda") on a box that has CUDA. On a CPU runner torch warns "CUDA is not available. Disabling" and hands back a no-op, so the premise test would not have raised and every enabled case would have read False, failing for reasons unrelated to the code. Measured, then fixed by claiming the device rather than skipping, since a CPU job is where these would most need to run. They pass with the GPUs visible and with CUDA_VISIBLE_DEVICES empty. Tests: 4386 passed, same 1310 environment failures as the branch base, nothing failing here that is not also failing there. * Size the GRPO chunk on the dtype the forward runs in The autocast-off branch assumed float32, but pure bfloat16 full finetuning also disables autocast (ACCELERATE_MIXED_PRECISION='no') while keeping bf16 weights and a bf16 forward. That path got dtype_bytes=32 where main gave 16, cutting the chunk ~1.5x and doubling the forward-pass count on 10-22GB cards. Read lm_head.dtype instead: float32 for an explicit float32 load, bfloat16 here. Retargets the test that pinned the old value. * Apply ruff kwarg-spacing formatting pre-commit.ci's ruff-format-with-kwargs hook reported "files were modified by this hook" and could not push the result back, so the check stayed red. Applied locally instead. Three source-asserting tests had to be made robust rather than re-pinned, since the reformatting is legitimate and will happen again: - test_the_flag_is_recorded_beside_the_dtype counted the literal "self._autocast_enabled = (", which the formatter collapsed onto one line. Now pairs each _autocast_dtype initialiser with a nearby flag assignment by position, so it still catches a genuinely missing one. - test_the_original_error_is_still_reported anchored on a whole f-string literal, which the formatter merged with the hint that follows it. Anchors on the message text alone now; either shape satisfies the intent. - test_the_source_beats_the_version_fallback exposed a real fragility rather than a test problem: the detector matched the literal "kw_only=True", so any whitespace in transformers' own source would have read an install that needs nothing as one that needs patching. Made whitespace-tolerant. * Latch the GRPO autocast decision on the trainer * Add the license header to the new test files * Stamp the forced float32 answer on the model UNSLOTH_FORCE_FLOAT32 is process wide and from_pretrained clears it on every load, so a model loaded after a Gemma3 or gpt-oss trainer was built left '0' behind and GRPO's first generation dropped the float16 autocast that rl.py's 'no' was written expecting, running generation in full float32. The loaders now stamp the answer on the model they loaded, next to the existing float32 request marker, and the trainer reads it from there. Models without the stamp fall back to the environment as before. * Preserve a bf16 trainer when a forced-float32 model was loaded (#7867) * Stamp the forced float32 answer on every loader return path (#7867) * Stamp the float32 answers on the text-diffusion dispatch (#7867) * Apply the repo ruff-format hook to a test touched by this PR * Apply the repo ruff-format hook (ruff 0.6.9) to files this PR touches * Fix the trainer reading the process-wide forced float32 flag for PR #7867 * Fix a missing optional dependency aborting the whole pytest session for PR #7867 require_package exited the process when a system package was absent. The TTS test modules call it at import time, so under pytest the SystemExit escaped collection and ended the run with INTERNALERROR / exit code 3 instead of skipping one file. It now degrades to a module-level skip under pytest, the same treatment require_python_package already had, and keeps the exit for the standalone script callers. test_whisper.py also imported the unsloth runtime unguarded, which is a collection error on the Windows runner where triton is absent; guard it with a module-level skip. * Inherit an outer autocast by omitting dtype, not by a sentinel * Read the forced float32 stamp inside native fast generation * Stamp the full finetuning mode on the model the trainer reads * Keep one missing-dependency helper after the merge with main The merge left this branch's _skip_if_pytest alongside main's _missing_dependency, doing the same job, plus two near-duplicate test files. Fold both into main's helper and its test module, keeping this branch's extra coverage of require_package and of the call at module scope. * Make the generation autocast tests independent of the host having CUDA torch.autocast(device_type = 'cuda') disables itself when CUDA is absent, so reading _enabled off the constructed object measured the runner instead of the branch, and these could never pass on a CPU-only machine, a Mac or Windows. Record the arguments the code asks for instead. Also skip before importing rl_replacements, which needs unsloth_zoo. * Apply the repo's ruff kwarg-spacing formatting * Format these three files with the ruff the hook actually pins The ruff-format-with-kwargs hook installs ruff==0.6.9 through additional_dependencies, and 0.6.9 and 0.15 disagree on where the message goes in a multi-line assert and on how a long lambda signature wraps. I had run the script with the workspace ruff, so pre-commit.ci kept reformatting these back and failing, with nothing to show in the diff. AST is identical on all three. * Drop the nullcontext import this PR no longer uses Left over from the earlier shape of the autocast gating, which now omits dtype instead of passing a sentinel context. Source lint's import-hoist check treats an added-but-unused hoisted import as a blocker, and it is right: nothing in this file references it. * Tighten comments for the float32 dtype gating change --------- Co-authored-by: danielhanchen <[email protected]>
float32 on a GPU with no bfloat16
Asking for
dtype = torch.float32on a T4 or V100 did not get you float32 training. With neither precision flag set, the mixed-precision block picked an autocast, and the only one available without bf16 is float16, whose exponent range is far narrower. Values overflow toinfand then toNaN.The model now stays in float32 in that case, and says so.
Why it is gated on an explicit request
This is the part worth reading twice, because the first version of the fix was too eager and broke #4082.
Full finetuning upcasts weights to float32 by itself, and float16 autocast over float32 master weights is the normal V100/T4 recipe. So "dtype is float32" is not enough to justify turning autocast off: it is true both when the user asked for float32 and when the loader arrived there on its own, and those want opposite behaviour.
from_pretrainednow recordsUNSLOTH_USER_FLOAT32only when the caller passeddtype = torch.float32themselves, and the new branch requires that flag. It is written on every load, so a stale"1"cannot leak from one model to the next. bf16 GPUs are unaffected either way, since bf16 has float32's exponent range.tests/python/test_v100_fullft_precision.py, the #4082 regression guard that the first version broke, passes on this branch.Test session no longer dies on one optional audio dependency
A missing optional package aborted the whole pytest session at import time instead of skipping the module that needed it.
require_python_packagenow skips with the package named.Tests
tests/test_float32_no_fp16_autocast.py: 13 passed, 0 failed, 0 skippedtests/utils/: 159 passed, 2 skipped, 0 failed (both skips pre-existing)On what is and is not really tested: the no-bfloat16 path cannot be exercised on hardware here, because the GPU available supports bf16. The tests fake the capability check, stubbing
device_is_bf16_supported()andtorch.cuda.is_bf16_supported()to return the requested answer, and asserting the stub rather than the fallback import was the one used. The generated mixed-precision block is extracted fromrl.pyby AST and executed against fakeargsandmodelobjects. So both bf16 answers are covered end to end as logic, but the real T4 NaN scenario has not been reproduced on a T4 as part of this change.tests/saving/text_to_speech_models/test_whisper.pywas AST-parsed but not executed; it needs a model download and a Wikimedia fetch.The T4 scenario has now been reproduced, and this is what fixes it
The caveat above ("the real T4 NaN scenario has not been reproduced on a T4 as part of this change") is out of date. It has since been hit on real T4s, repeatedly, by
Spark_TTS_(0_5B).ipynb.That notebook loads with
dtype = torch.float32, full_finetuning = Trueand passesfp16 = False, bf16 = FalsetoSFTConfig, which is exactly the shape this PR is about. On a T4 it trains toNaNfrom step 1.Colab evidence
17 runs of that notebook across Colab T4 and L4 lanes. The outcome tracks one line of output with no exceptions:
Unsloth: Model is in float32 and this GPU has no bfloat16 support...(this PR)NaNat every stepThe unsloth and unsloth_zoo versions, torch, transformers, trl, peft and bitsandbytes are byte-identical between the passing and failing runs. The only difference is whether this branch is present.
One run is worth calling out: it printed the loader-side
Using float32 full finetuning.message but not the trainer-side one, and it failed. The loader half alone is not enough. Therl.pymixed-precision branch is the part that does the work.What the NaN turns into
The notebook does not report a NaN. It reports this, two cells later:
Under
CUDA_LAUNCH_BLOCKING=1the assert names itself:NaN weights, NaN logits, NaN probabilities, and
torch.multinomialrefuses them. The assert then poisons the CUDA context, so the followingsave_pretrainedfails with the same error fromtensor.to("cpu")and looks like a third, unrelated bug. It is not an out-of-range token id, which is the usual reading of a device-side assert in a TTS model.Local reproduction
A standalone script (not added to the repo: it needs the 2 GB
Spark-TTS-0.5Bdownload and a GPU, so it is not a unit test) runs the notebook's load and trainer configuration againstSpark-TTS-0.5B/LLMwithunsloth_zoo.device_type.device_is_bf16_supportedstubbed toFalse, which is the whole of what makes a T4 different for this code path. Same GPU, same data, same seed, only the branch differs:args.fp16after constructionACCELERATE_MIXED_PRECISIONTrue(despitefp16 = False)fp16NaNx7FalsenoNote the first column: on main the trainer silently turns
fp16back on after the caller explicitly set it toFalse.Sabotage check on the branch itself, so the test is not vacuous: disabling the new
elifreproduces main exactly (args.fp16 = True,NaNx7, exit 3); restoring it returns the same seven losses as above, to the digit (exit 0).On a GPU that really does have bfloat16, main and this branch produce identical trainer settings (
bf16autocast,args.fp16 = False) and identical results, which is the intended blast radius: the branch is gated onnot _bf16_supported()and cannot fire there.