Repository navigation
Fix full finetuning precision on V100 / no-bf16 GPUs - #5880
Conversation
Float16 full finetuning upcasts weights to float32, so the model dtype is float32, not bfloat16. The SFTTrainer precision template treated 'not float16' as 'bfloat16', which broke full finetuning on V100/T4: the dtype guard rejected float32 + fp16, and the auto mixed precision branch forced bf16 on hardware without it. FORCE_FLOAT32 models (Gemma3, gpt_oss, gemma3n, qwen3_5) were also only kept in float32 for LoRA, so full finetuning fell through to fp16 and produced NaNs. Distinguish bfloat16 from float32 in the guard, pick bf16 in the auto branch only when the GPU supports it (else fp16), and apply force_float32 for FORCE_FLOAT32 models in full finetuning too. bf16 GPUs are unchanged.
There was a problem hiding this comment.
Code Review
This pull request updates the RL trainer patching logic in unsloth/models/rl.py to improve mixed precision training configuration. It ensures that models requiring float32 training remain in float32, refines the bfloat16 validation, and dynamically checks for bfloat16 support via torch.cuda.is_bf16_supported(). Feedback on this PR suggests further safeguarding the bfloat16 check by verifying that the GPU's compute capability is at least 8.0, as torch.cuda.is_bf16_supported() can incorrectly return True on T4 GPUs in some PyTorch versions.
| " os.environ['ACCELERATE_MIXED_PRECISION'] = 'fp16' if float16 else 'bf16'\n" | ||
| " if hasattr(args, 'mixed_precision'): args.mixed_precision = 'fp16' if float16 else 'bf16'\n" | ||
| " # Mixed precision training. bf16 only if the GPU supports it; V100/T4 use fp16.\n" | ||
| " use_bf16_amp = (not float16) and torch.cuda.is_bf16_supported()\n" |
There was a problem hiding this comment.
On certain PyTorch versions (such as PyTorch 2.3), torch.cuda.is_bf16_supported() has a known bug where it can incorrectly return True on T4 GPUs (which only have compute capability 7.5 and do not support bfloat16).
To prevent this from causing runtime crashes or extremely slow training on T4 GPUs, it is safer to also verify that the GPU's compute capability is at least 8.0 using torch.cuda.get_device_capability()[0] >= 8.
| " use_bf16_amp = (not float16) and torch.cuda.is_bf16_supported()\n" | |
| " use_bf16_amp = (not float16) and torch.cuda.is_bf16_supported() and torch.cuda.get_device_capability()[0] >= 8\n" |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8b1611c26c
ℹ️ 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".
| " os.environ['ACCELERATE_MIXED_PRECISION'] = 'fp16' if float16 else 'bf16'\n" | ||
| " if hasattr(args, 'mixed_precision'): args.mixed_precision = 'fp16' if float16 else 'bf16'\n" | ||
| " # Mixed precision training. bf16 only if the GPU supports it; V100/T4 use fp16.\n" | ||
| " use_bf16_amp = (not float16) and torch.cuda.is_bf16_supported()\n" |
There was a problem hiding this comment.
Preserve bf16 on non-CUDA devices
When RL trainers run on an XPU backend with bf16 support, this CUDA-only probe returns false (or otherwise does not reflect torch.xpu.is_bf16_supported()), so the generated trainer now forces args.fp16=True and ACCELERATE_MIXED_PRECISION=fp16 even though the rest of the project detects XPU bf16 via torch.xpu.is_bf16_supported() in _gpu_init.py. This regresses the default bf16 path for supported non-CUDA devices; use the existing device-aware support check instead of torch.cuda here.
Useful? React with 👍 / 👎.
Exercise the real SFTTrainer mixed-precision template from rl.py source against mocked inputs: normal models get float32 weights + fp16 forward, FORCE_FLOAT32 models stay pure float32, no bf16 on no-bf16 hardware, and bf16 GPUs are unchanged. Covers issue #4082.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cca441f125
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| "if not full_finetuning and (os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '1'):\n" | ||
| # FORCE_FLOAT32 models (Gemma3, gpt_oss, ...) cannot use float16; keep | ||
| # them in float32 even for full finetuning so V100/T4 never autocast to fp16. | ||
| "if os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '1':\n" |
There was a problem hiding this comment.
Keep GRPO forced-float32 paths out of fp16 autocast
When UNSLOTH_FORCE_FLOAT32=1 is now honored for full finetuning, this branch sets the trainer to pure float32, but GRPO still wraps generation/logprob code in fp16 autocast whenever that same env var is set (rl_replacements.py forces torch.float16 in _prepare_inputs and _get_per_token_logps*). In FORCE_FLOAT32 full-FT GRPO runs, the model can still hit the fp16 path this change is trying to avoid, so the NaN regression remains for those trainers unless the GRPO autocast replacements are also disabled or made float32-aware.
Useful? React with 👍 / 👎.
The auto mixed-precision branch now gates bf16 on unsloth_zoo's device_is_bf16_supported() (CUDA/XPU/HIP) instead of torch.cuda.is_bf16_supported(), which is only patched on CUDA. This keeps V100/T4 on fp16 while leaving AMD (HIP) and Intel (XPU) behavior unchanged. Falls back to the torch call on older unsloth_zoo.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 690185abe1
ℹ️ 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".
| sys.modules.setdefault("unsloth_zoo", uz) | ||
| sys.modules["unsloth_zoo.utils"] = uzu | ||
| sys.modules["unsloth_zoo.device_type"] = uzd |
There was a problem hiding this comment.
Restore stubbed unsloth_zoo modules after each decision
When this helper runs in the same pytest process as the rest of the suite, these assignments replace unsloth_zoo, unsloth_zoo.utils, and unsloth_zoo.device_type in sys.modules and never restore the previous entries. Any later test/import that expects the real modules can instead see stubs that only define _get_dtype/device_is_bf16_supported (or a root module with no __spec__), causing order-dependent failures or false positives; save and restore these entries with monkeypatch or a try/finally.
Useful? React with 👍 / 👎.
|
Validated on a real Tesla T4 (sm_75, no native bf16, CUDA 13.0 driver, torch 2.11.0+cu128, transformers 4.57.6, trl 0.25.1). I compared stock main against this branch in isolated venvs. Summary: the precision selection is correct on a no-bf16 GPU across SFT, eval, GRPO codegen, and the bfloat16 load path. Results
One separate issue, not this PR's precision logic: GRPO full finetuning cannot complete a step on a no-bf16 GPU. Compiled it fails with a Dynamo shape error in LGTM on my end. |
|
Stack confirmed end-to-end on a real Tesla T4. With this PR plus unsloth #5898 and unsloth_zoo #707 + #709, GRPO full finetuning trains 10/10 steps on a no-bf16 T4 in both eager and compiled modes (DECISION fp16=True bf16=False AMP=fp16, finite train_loss, rewards and KL computed, no index_copy_ and no logits-shape error). LoRA is unaffected. Full end-to-end results are on #5898 and unsloth_zoo #709. |
FORCE_FLOAT32 models (Gemma3, gpt_oss, qwen3_5) cannot use float16. Forcing float32 is required on GPUs without bf16 (V100/T4) so they never autocast to fp16, but on a bf16-capable GPU full finetuning can use bf16 autocast (the master weights stay float32), which is faster and uses less memory. Gate the force-float32 switch to skip full finetuning when bf16 is supported; LoRA/QLoRA still go to float32 when forced.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e0becf489f
ℹ️ 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".
| # faster and uses less memory; LoRA/QLoRA keep float32 when forced. | ||
| "full_finetuning = os.environ.get('UNSLOTH_ENABLE_FULL_FINETUNING', '0') == '1'\n" | ||
| "if not full_finetuning and (os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '1'):\n" | ||
| "if os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '1' and not (full_finetuning and _bf16_supported()):\n" |
There was a problem hiding this comment.
Reject fp16 for FORCE_FLOAT32 full finetuning
When UNSLOTH_FORCE_FLOAT32=1 full finetuning runs on a bf16-capable device and the caller explicitly set args.fp16=True, this condition leaves force_float32 false; because the later auto-precision branch is skipped whenever use_fp16 is true, args.fp16 remains enabled. These models are marked FORCE_FLOAT32 because they cannot use float16, so this path can still put Gemma3/gpt_oss-style full-FT runs under fp16 autocast instead of coercing to bf16/float32 or raising.
Useful? React with 👍 / 👎.
|
Notebook regression sweep on a real Tesla T4 (sm_75, no native bf16, torch 2.11.0+cu128, transformers 4.57.6, trl 0.25.1). I ran a batch of Unsloth notebooks twice each, back to back on the same GPU and seed, to check this PR stack does not change behaviour versus released main:
Result: every notebook that trains selected the SAME precision under the PR stack as on stock, and produced bit-identical (or within fp16 noise) per-step loss, grad-norm, peak memory and time. No bf16 was ever selected on the T4. 0 regressions.
The full-finetuning case (bert_classification, Eight other notebooks fail, but every one fails identically on stock too, so none are caused by this PR stack:
Net: this PR keeps LoRA/QLoRA/full-FT numerics identical to main while fixing the no-bf16 precision selection. LGTM. |
|
Verified your fix on a real GPU box. On released main the same full finetune crashes at SFTTrainer construction with the One follow-up: the regression test stubbed Merging. |
Summary
Full finetuning on a GPU without bfloat16 (V100, T4) failed with
TypeError: Unsloth: Model is in bfloat16 precision but you want to use float16 precision, or crashed later in Accelerator after a bf16 request. Closes #4082.Float16 full finetuning upcasts the weights to float32, so the model dtype is float32, not bfloat16. The SFTTrainer precision template treated "not float16" as "bfloat16", which breaks in two ways on a no-bf16 GPU, and a third related problem affected the FORCE_FLOAT32 models:
bf16 = not float16, forcing bf16 on hardware that has none.Changes
All in
unsloth/models/rl.py, the template that generates the SFTTrainer mixed precision block:bfloat16 = dtype == torch.bfloat16and make the second dtype guard fire onbfloat16 and use_fp16instead ofnot float16 and use_fp16, so a float32 model plus fp16 is allowed.unsloth_zoo.device_type.device_is_bf16_supported()(CUDA, XPU and HIP aware), falling back totorch.cuda.is_bf16_supportedon older unsloth_zoo, so NVIDIA V100/T4 get fp16 while AMD and Intel paths are unaffected. On a bf16 GPU this is identical to the oldbf16 = not float16; only no-bf16 GPUs change (they get fp16 instead of an unsupported bf16).force_float32wheneverUNSLOTH_FORCE_FLOAT32=1, including full finetuning, so FORCE_FLOAT32 models stay in pure float32 on V100 instead of autocasting to fp16.Intended behavior on a no-bf16 GPU: full finetuning keeps the trainable (master) weights in float32 and runs the forward pass under float16 autocast. Models that cannot use float16 (the FORCE_FLOAT32 set) instead keep a pure float32 forward.
Precision matrix on a no-bf16 GPU (V100 / T4)
bf16-capable GPUs are unaffected on the default precision path (
fp16andbf16left unset), which covers LoRA, QLoRA and the common full finetuning flow: change 2 is algebraically identical to the previous behavior whenis_bf16_supported()is true, andUNSLOTH_FORCE_FLOAT32is only auto-set on no-bf16 or fp16 load paths. The one difference on a bf16 GPU is that an explicitfp16=Trueon a float32 config model no longer raises the spuriousTypeErrorfrom change 1 (the oldnot float16guard over-fired on float32). A genuine bfloat16 model withfp16=Truestill raises.Validation
Verified on a compute-capability-7.0 (no bf16) configuration:
fp16=Trueand unset-precision configs.fp16=False,bf16=False), never fp16 or bf16.