Skip to content

Fix full finetuning precision on V100 / no-bf16 GPUs - #5880

Merged
oobabooga merged 8 commits into
mainfrom
fix-v100-fullft-precision
Jun 29, 2026
Merged

oobabooga merged 8 commits into
mainfrom
fix-v100-fullft-precision

Conversation

@danielhanchen

@danielhanchen danielhanchen commented May 31, 2026 •

Copy link
Copy Markdown
Member

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:

  1. The dtype guard rejected a float32 model whenever fp16 was requested.
  2. The auto mixed precision branch set bf16 = not float16, forcing bf16 on hardware that has none.
  3. FORCE_FLOAT32 models (Gemma3, gpt_oss, gemma3n, qwen3_5) that cannot use float16 were only kept in float32 for LoRA, not full finetuning, so on a V100 they fell through to fp16 autocast and produced NaNs.

Changes

All in unsloth/models/rl.py, the template that generates the SFTTrainer mixed precision block:

  1. Add bfloat16 = dtype == torch.bfloat16 and make the second dtype guard fire on bfloat16 and use_fp16 instead of not float16 and use_fp16, so a float32 model plus fp16 is allowed.
  2. In the auto mixed precision branch, select bf16 only when the device actually supports it, else fp16. This uses unsloth_zoo.device_type.device_is_bf16_supported() (CUDA, XPU and HIP aware), falling back to torch.cuda.is_bf16_supported on 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 old bf16 = not float16; only no-bf16 GPUs change (they get fp16 instead of an unsupported bf16).
  3. Apply force_float32 whenever UNSLOTH_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)

Case Before After
Normal model, full FT, fp16=True TypeError float32 weights + fp16 forward
Normal model, full FT, fp16/bf16 unset bf16 set, then crash float32 weights + fp16 forward
FORCE_FLOAT32 model (Gemma3, gpt_oss, ...), full FT fp16 autocast, NaN pure float32
LoRA / QLoRA unchanged unchanged

bf16-capable GPUs are unaffected on the default precision path (fp16 and bf16 left unset), which covers LoRA, QLoRA and the common full finetuning flow: change 2 is algebraically identical to the previous behavior when is_bf16_supported() is true, and UNSLOTH_FORCE_FLOAT32 is only auto-set on no-bf16 or fp16 load paths. The one difference on a bf16 GPU is that an explicit fp16=True on a float32 config model no longer raises the spurious TypeError from change 1 (the old not float16 guard over-fired on float32). A genuine bfloat16 model with fp16=True still raises.

Validation

Verified on a compute-capability-7.0 (no bf16) configuration:

  • A normal model (Qwen2.5) in full finetuning now initializes and selects fp16 autocast for both fp16=True and unset-precision configs.
  • A FORCE_FLOAT32 model (gemma-3) in full finetuning stays in pure float32 (fp16=False, bf16=False), never fp16 or bf16.
  • bf16-capable behavior (pure bf16 full finetuning, bf16 autocast) is unchanged.

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread unsloth/models/rl.py Outdated
" 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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
" 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"

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/rl.py Outdated
" 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"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/rl.py Outdated
"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"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +63 to +65
sys.modules.setdefault("unsloth_zoo", uz)
sys.modules["unsloth_zoo.utils"] = uzu
sys.modules["unsloth_zoo.device_type"] = uzd

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

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

  • Normal-model full finetuning, default precision (dtype=None): on main this crashes at SFTTrainer construction with ValueError: bf16 mixed precision requires PyTorch >= 1.10 and a supported device. The auto path sets bf16 = not float16, which forces bf16 on float32 full-FT weights. With this branch it selects fp16=True, bf16=False, ACCELERATE_MIXED_PRECISION=fp16 and trains to a finite loss.
  • LoRA and QLoRA: unchanged. Per-step losses are bit-identical to main (the change is algebraically identical for a float16 model).
  • Eval path (eval_strategy=steps, eval_steps=2): fp16_full_eval=True, bf16_full_eval=False, eval runs with finite losses.
  • bfloat16 load: from_pretrained(dtype=torch.bfloat16, full_finetuning=True) on the T4 downgrades to fp16 and trains, no "supported device" error, same final loss as the dtype=None run.
  • Save, reload, generate after a full-FT run: works, output is coherent.
  • GRPO: the precision block codegens correctly into GRPOTrainer (fp16=True, bf16=False).

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 chunked_hidden_states_selective_log_softmax. Eager (UNSLOTH_COMPILE_DISABLE=1) it fails with RuntimeError: index_copy_(): self and source expected to have the same dtype, but got (self) Float and (source) Half. The precision selection is fine, this is a dtype mismatch in the GRPO path. I will open a separate issue.

LGTM on my end.

@danielhanchen

Copy link
Copy Markdown
Member Author

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/rl.py
# 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"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

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.

Notebook Precision (stock / PR) max abs loss diff peak MB (s/p)
bert_classification (ModernBERT-large, FULL finetuning) float16 / float16 0.0 4318 / 4318
Llama3.2_(1B_and_3B)-Conversational float16 / float16 0.0 6309 / 6309
Deepseek_OCR_(3B) float16 / float16 3.1e-3 8536 / 8536
Gemma3N_(4B)-Vision float32 (FORCE_FLOAT32) / float32 0.0 14571 / 14571
Qwen3_(4B)_Instruct-QAT float16 / float16 0.0 11085 / 11085
Mistral_(7B)-Text_Completion float16 / float16 0.0 9356 / 9356
Mistral_v0.3_(7B)-Conversational float16 / float16 0.0 8937 / 8937
Llama3.1_(8B)-Alpaca float16 / float16 0.0 7073 / 7073
Llama3_(8B)-Ollama float16 / float16 0.0 8047 / 8047
Qwen3_VL_(8B)-Vision float16 / float16 3.0e-4 8620 / 8620

The full-finetuning case (bert_classification, full_finetuning = True, 396M params 100% trained) is the most relevant to this PR: it selects fp16=True bf16=False AMP=fp16 and trains finite on both stock and the PR stack, no bf16 device error.

Eight other notebooks fail, but every one fails identically on stock too, so none are caused by this PR stack:

  • Gemma3_(4B)-Vision and Gemma3_(4B)-Vision-GRPO: gemma3 forced-float32 vision path (dtype mismatch / OOM), see unsloth_zoo ImportError: cannot import name 'AutoPeftModelForCausalLM' from 'peft' #706.
  • Gemma3N_(4B)-Audio: torch.compile Dynamo Unsupported Tensor.requires_grad_() in the audio path.
  • Mistral_v0.3_(7B)-CPT: CUDA OOM at step 4 on 15GB (CPT trains embed+lm_head); first 3 steps were bit-identical stock vs PR.
  • Sesame_CSM_(1B)-TTS, Whisper, Orpheus_(3B)-TTS: their dataset MrDragonFox/Elise returns HTTP 403 here (gated), fails before any model code.
  • Qwen3_VL_(8B)-Vision-GRPO: pre-existing vision GRPO generate error (mm_token_type_ids not accepted by generate()).

Net: this PR keeps LoRA/QLoRA/full-FT numerics identical to main while fixing the no-bf16 precision selection. LGTM.

@Datta0 Datta0 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@oobabooga

Copy link
Copy Markdown
Member

Verified your fix on a real GPU box. On released main the same full finetune crashes at SFTTrainer construction with the bf16 mixed precision requires ... a supported device ValueError from #4082; on your branch it selects fp16=True, bf16=False and trains to a finite loss. The bf16 path is untouched on real bf16 hardware (pure bf16, no autocast). I have no V100/T4 here, so I forced device_is_bf16_supported() off to exercise the no-bf16 selection, and your real-T4 run covers the hardware. Fork CI green.

One follow-up: the regression test stubbed sys.modules and env vars without restoring them, leaking into later tests; I wrapped it in save and restore. Your precision logic is unchanged.

Merging.

@oobabooga
oobabooga merged commit de3c745 into main Jun 29, 2026
50 of 51 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] V100 cannot perform full fine-tuning of BF16 models

3 participants