Skip to content

GPUs without bfloat16 (RX 5000 / 6000, T4, V100): load outlier-prone models (Gemma, gpt-oss, Qwen3.5) in float32 - #11533

Closed
danielhanchen wants to merge 1 commit into
mainfrom
fix/force-float32-without-bfloat16
Closed

danielhanchen wants to merge 1 commit into
mainfrom
fix/force-float32-without-bfloat16

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The bug

The FORCE_FLOAT32 families (gemma3, gemma3n, gemma4, glm4_moe, gpt_oss, qwen3_5, qwen3_moe) have activations outside float16's finite range, so they are loaded in bfloat16 instead. bfloat16 is the deliberate choice there: it reduces the outliers that make float16 unusable for them.

The selection branch is entered when the caller asked for float16 or the device has no bfloat16, and it then chose bfloat16 unconditionally. On the second of those two conditions that picks the one dtype the device cannot run.

# loader.py, before
) and ((dtype == torch.float16) or not SUPPORTS_BFLOAT16):
    dtype = torch.bfloat16  # Change to bfloat16 loading

Two ways it surfaces:

vision.py made it unrecoverable. Its FORCE_FLOAT32 branch is an elif, so promoting float16 to bfloat16 there skips the dtype == bfloat16 and not SUPPORTS_BFLOAT16 downgrade directly beneath it, and nothing is left to correct the choice.

The fix

float32 is the remaining dtype that still honours "must not run in float16", so that is the fallback. bfloat16 is unchanged wherever it is usable.

The rule is one helper, force_float32_dtype(), called from both sites, because the two copies had already drifted apart. No new detection is added: SUPPORTS_BFLOAT16 already answers False for gfx10 via device_type.arch_lacks_bf16(), which _gpu_init.py uses to override torch.cuda.is_bf16_supported().

Non-RDNA2 devices are provably unchanged

Not "no regression observed": the decision is the same object. force_float32_dtype(True) is torch.bfloat16, and the added disjunct is always False on a bf16 device. Over (SUPPORTS_BFLOAT16 x incoming dtype):

supports bf16 dtype in loader before -> after vision before -> after
True None bfloat16 -> bfloat16 None -> None
True float16 bfloat16 -> bfloat16 bfloat16 -> bfloat16
True bfloat16 bfloat16 -> bfloat16 bfloat16 -> bfloat16
True float32 bfloat16 -> bfloat16 float32 -> float32

8 of 8 cells identical for NVIDIA Ampere and newer, RDNA3/3.5/4, CDNA and XPU. Only the no-bfloat16 half moves, 6 of 8 cells.

The arch gate does not over-reach either: gfx1100, gfx1151, gfx1201, gfx90a and gfx942 all keep bfloat16, and an unreadable arch fails open, so a detection failure never pushes a working GPU onto float32.

Performance

The added call costs 0.083 us, once per from_pretrained(). It is in no training step, no decode loop and no per-layer path, so throughput and memory cannot move on a bfloat16 device.

Tests

tests/test_force_float32_without_bfloat16.py, 17 cases: bfloat16 is still chosen wherever it works, float32 replaces it only where it does not, float16 is never the answer, the gfx10 prefix stays 5 characters so RDNA3/3.5/4 are untouched, unreadable archs fail open, and both call sites go through the shared helper.

Regression check, same file set on both sides:

  • test_float32_generate_autocast, test_float32_no_fp16_autocast, test_bf16_quant_disabled_message, test_attn_dtype_custom_datatype: 46 passed before and after.
  • Full loader / vision / dtype / device selection: 3623 passed, 3 skipped, 0 failed, identical on both trees.

What this does not cover

No RDNA2 or pre-Ampere hardware was available, so the fix is evidenced by the decision table and the test suite, not by a run on a gfx1034 or a T4.

One adjacent hole is left alone deliberately: when dtype is None, that branch runs before the FORCE_FLOAT32 check, so a no-bfloat16 device still gets float16. The only signal available at that point is the process-wide UNSLOTH_FORCE_FLOAT32, which the surrounding comments already flag as stale across multiple loads, so acting on it there could make matters worse. Worth a separate look.

Companion to unslothai/unsloth-zoo#1316, which fixes the gradient checkpointing side (an offloaded activation was handed back in the staging buffer's dtype). The two are independent and neither depends on the other.

The FORCE_FLOAT32 families (gemma3, gemma3n, gemma4, glm4_moe, gpt_oss,
qwen3_5, qwen3_moe) have activations outside float16's finite range, so they
are loaded in bfloat16 instead: bfloat16 is the deliberate choice because it
reduces the outliers that make float16 unusable for them.

The selection branch is entered when the caller asked for float16 OR the
device has no bfloat16, and it then chose bfloat16 unconditionally. On the
second of those two conditions that picks the one dtype the device cannot run:

  RDNA 1/2 (gfx101x, gfx103x) cannot lower bfloat16 in Triton, so the tensor
  reaches a kernel and LLVM aborts the whole process with no Python exception,
  "Cannot select: intrinsic %llvm.amdgcn.fdot2.bf16.bf16" (#7922).

  Pre-Ampere NVIDIA (T4, V100) raises "expected mat1 and mat2 to have the same
  dtype, but got: BFloat16 != Half" (#7506).

vision.py made it unrecoverable: its FORCE_FLOAT32 branch is an `elif`, so
promoting float16 to bfloat16 there skipped the `dtype == bfloat16 and not
SUPPORTS_BFLOAT16` downgrade directly beneath it and nothing was left to
correct the choice.

float32 is the remaining dtype that still honours "must not run in float16",
so that is the fallback. bfloat16 is unchanged wherever it is usable.

The rule is one helper, force_float32_dtype(), called from both sites, because
the two copies had already drifted. No new detection: SUPPORTS_BFLOAT16
already answers False for gfx10 via device_type.arch_lacks_bf16(), which
_gpu_init.py uses to override torch.cuda.is_bf16_supported().

Measured on a bf16-capable device the decision is byte-identical: over
(SUPPORTS_BFLOAT16 x incoming dtype), 8 of 8 cells unchanged, because
force_float32_dtype(True) is torch.bfloat16 and the added disjunct is always
False there. Only devices without bfloat16 change, 6 of 8 cells. The added
call costs 0.083 us once per from_pretrained(), and is in no training step,
decode loop or per-layer path. tests/test_float32_generate_autocast.py,
test_float32_no_fp16_autocast.py, test_bf16_quant_disabled_message.py and
test_attn_dtype_custom_datatype.py: 46 passed before and after, unchanged.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-22T13:13:32.431209Z 05236b9 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 05236b959b

ℹ️ 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/vision.py
Comment on lines +1352 to +1353
if dtype == torch.float16 or (dtype == torch.bfloat16 and not SUPPORTS_BFLOAT16):
dtype = force_float32_dtype(SUPPORTS_BFLOAT16)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve the float32 fallback through the actual model load

On a device without bfloat16, this correctly changes dtype to float32, but every normal FORCE_FLOAT32 load still sets do_forced_float32 = True, after which lines 1415–1417 unconditionally replace the actual torch_dtype with torch.bfloat16. That value is then used by the device-map planner, attention resolver, and from_pretrained, so RDNA1/2 and pre-Ampere NVIDIA devices still receive the unsupported bfloat16 tensors this change is intended to eliminate. The later override must retain float32 when SUPPORTS_BFLOAT16 is false.

Useful? React with 👍 / 👎.

@LeoBorcherding

LeoBorcherding commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

ran this on the RX 6500 XT (gfx1034), windows 11, torch 2.11.0+rocm7.13.0, triton-windows 3.8.0. upstream main wants newer deps than the studio venv has, so i applied the three source hunks onto the installed 2026.9.7 and put that copy first on PYTHONPATH, everything else untouched. the decision table file passes here with the card really answering no bf16: 17 passed, SUPPORTS_BFLOAT16 = False, arch_lacks_bf16("gfx1034") = True, force_float32_dtype() -> torch.float32.

every run below is SFTTrainer, seq 1024, batch 2, ~1000 tokens per row, dtype=torch.float16 passed in like Studio does unless noted.

what the dtype ends up as on this card

Qwen3.5-0.8B 16-bit LoRA, before and after the PR:
    weight dtypes {'torch.float16': '852.9M', 'torch.float32': '0.1M'}   model.dtype torch.float16
before the PR:  GC init dtype torch.bfloat16
after the PR:   GC init dtype torch.float32

the weights come out float16 both ways (vision.py loads bf16 when the family is forced and patch_model_and_tokenizer casts to float16), and the new dtype goes to apply_unsloth_gradient_checkpointing(..., dtype), so the staging buffers are float32 now. same with dtype=None passed in.

with stock unsloth_zoo 2026.9.6

run main this PR
Qwen3.5-0.8B 16-bit LoRA BFloat16 != Half float != c10::Half
same, dtype=None BFloat16 != Half float != c10::Half
Qwen3.5-0.8B QLoRA LLVM abort fdot2.bf16.bf16 triton OutOfResources: shared memory, Required: 73728, Hardware limit: 65536
Qwen3.5-2B QLoRA LLVM abort same OutOfResources
gemma-3-270m 16-bit LoRA, 6 steps trains trains, 0.0592 0.0592 0.0330 0.0233 0.0188 0.0165, tracks the no-offload reference

the failures are all in the checkpoint recompute (gradient_checkpointing.py:1081 in backward), which is the unslothai/unsloth-zoo#1316 bug: the recompute input comes back in the buffer dtype, now float32 against fp16 weights. the QLoRA ones get past the bnb linears and reach fla's chunk_gated_delta_rule_fwd_h in fp32, which wants 72 KB of LDS with every config fla ships for a card this size, and rdna2 has 64 KB. so no more LLVM abort, its a python error now, which is already a nicer place to be.

gemma gets better from this alone: its activations are fp32, so fp32 buffers mean stock zoo stops squeezing them through bf16.

with unslothai/unsloth-zoo#1316 in

Qwen3.5-0.8B 16-bit LoRA trains 3/3, losses identical to 10 decimals to #1316 without this PR (0.0366736986 0.0366736986 0.0281048398), peak 2.26 GB. so the two together are the working combination on this card.

same under WSL2 ubuntu 24.04 (same card, torch 2.11.0+rocm7.13.0 linux wheels, triton 3.6.0, optim="adamw_torch" since bitsandbytes has no gfx103x kernels there)

run this PR, stock zoo this PR + #1316
Qwen3.5-0.8B 16-bit LoRA fp16 weights, fp32 buffers, float != c10::Half trains 3/3, 2.31 GB peak
same, dtype=None float != c10::Half n/a
gemma-3-270m 16-bit LoRA, 6 steps trains, 0.0591 0.0591 0.0324 0.0232 0.0188 0.0166 n/a

one thing for later if fp32 weights ever become the plan for these cards: fla's fp32 kernels dont fit rdna2's LDS with the current configs, and 0.8B in fp32 is ~3.4 GB of weights on a 4 GB card.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@LeoBorcherding LeoBorcherding self-assigned this Sep 25, 2026
@LeoBorcherding LeoBorcherding changed the title Fall back to float32, not bfloat16, when the device has no bfloat16 GPUs without bfloat16 (RX 5000 / 6000, T4, V100): load outlier-prone models (Gemma, gpt-oss, Qwen3.5) in float32 Sep 25, 2026
@LeoBorcherding

Copy link
Copy Markdown
Collaborator

@danielhanchen two findings from testing this next to unslothai/unsloth-zoo#1316. Your call whether to fix this PR or close it.

Short version

1. The float32 choice doesn't reach the model load

Background for anyone reading along: some model families (Qwen3.5, Gemma3, gpt-oss, ...) are marked FORCE_FLOAT32 because their activations overflow float16. They normally load in bfloat16 instead. This PR makes cards without bfloat16 pick float32 instead of bfloat16.

The pick happens at vision.py:1353:

if dtype == torch.float16 or (dtype == torch.bfloat16 and not SUPPORTS_BFLOAT16):
    dtype = force_float32_dtype(SUPPORTS_BFLOAT16)   # -> torch.float32 on these cards

But a few lines later, do_forced_float32 = True is set for every FORCE_FLOAT32 load, and at vision.py:1416 that overrides the dtype used for the load:

torch_dtype = dtype
if do_forced_float32:
    torch_dtype = torch.bfloat16

torch_dtype is what the device-map planner (add_dtype_kwargs(torch_dtype), line 1497), attention resolution (line 1419) and from_pretrained (line 1661) all receive. So the model still loads in bfloat16 and is cast to float16 afterwards.

This matches what I measured on the RX 6500 XT (gfx1034) in my comment above: Qwen3.5-0.8B weights come out torch.float16 both before and after this PR. The visible change is the dtype passed on to apply_unsloth_gradient_checkpointing, which moves the gradient-checkpoint offload buffers from bfloat16 to float32.

2. unslothai/unsloth-zoo#1316 already fixes the crash on RDNA2

The crash (LLVM ERROR: Cannot select: intrinsic %llvm.amdgcn.fdot2.bf16.bf16 on RDNA1/2, BFloat16 != Half elsewhere) comes from gradient checkpointing: an offloaded activation was handed back to the recompute in the offload buffer's dtype instead of its own. #1316 fixes that directly.

Qwen3.5-0.8B on the RX 6500 XT, dtype=torch.float16 passed in like Studio does:

setup 16-bit LoRA QLoRA
stock BFloat16 != Half LLVM abort
this PR, stock zoo float != c10::Half triton OutOfResources (shared memory)
#1316 alone trains trains (also 30/30 steps in Studio)
#1316 + this PR trains, losses identical to #1316 alone to 10 decimals not run

So with #1316 in, this PR changes nothing I could measure. Merged on its own before #1316, it turns the LLVM abort into a Python error, but Qwen3.5 still doesn't train.

gemma-3-270m does get better from this PR alone (its float32 activations stop going through bfloat16 buffers), but #1316 fixes that too, since it hands every activation back in its own dtype.

If you want to keep it

  • Keep float32 at vision.py:1416 when SUPPORTS_BFLOAT16 is false, so the weights actually load in float32.
  • Then it needs a real float32-weights run on a card without bfloat16. Two things I hit that may make float32 weights impractical on small RDNA2 cards: fla's float32 kernels ask for 72 KB of shared memory (Required: 73728, Hardware limit: 65536) where RDNA2 has 64 KB, and 0.8B in float32 is about 3.4 GB of weights on a 4 GB card.
  • pre-commit.ci fails only on the ruff-format-with-kwargs hook (formatting), and the rest of CI was cancelled, so it hasn't had a full run yet.

If not

Closing this in favour of unslothai/unsloth-zoo#1316 seems reasonable to me.

Not tested: pre-Ampere NVIDIA (T4, V100). A T4 run of #1316 is still pending, and that is the data point that would show whether this PR adds anything on those cards.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

follow-up to my last comment, and a correction to it: I suggested keeping float32 at vision.py:1416. Don't. On the RX 6500 XT (gfx1034), Windows 11, torch 2.11.0+rocm7.13.0, a float32 load leaves the weights split (183.4M fp32, 669.6M fp16), because zoo only converts bf16 leftovers (patching_utils.py:590). Qwen3.5-0.8B then dies with Half != float in Qwen3_5GatedDeltaNet_forward. That run was the change overlaid on 2026.9.12, and on a 4 GB card fp32 weights also cost twice the memory.

what works is staging in float16 when the device has no bf16:

         if do_forced_float32:
-            torch_dtype = torch.bfloat16
+            if SUPPORTS_BFLOAT16 or dtype == torch.bfloat16:
+                torch_dtype = torch.bfloat16
+            else:
+                torch_dtype = torch.float16

these runs are at the real SHAs (worktrees, same card):

RX 6500 XT, dtype=torch.float16        004351b (base)      05236b9 (this PR)    3405f7e (fp16 staging)
dtype into from_pretrained             bfloat16            bfloat16             float16
Qwen3.5-0.8B 3 SFT steps               0.0366659239 x2     0.0366659239 x2      0.0367048420 x2
                                       0.0281325746        0.0281325746         0.0281461794
gemma-3-270m-it weights vs 05236b9     n/a                 n/a                  bit-identical (236/236)

the small Qwen shift is the 18 linear_attn.norm.weight tensors, which the checkpoint stores in fp32. fp16 staging lands 8x closer to them than bf16 does (max err 0.000488 vs 0.00391). the dtype == torch.bfloat16 half is there for gpt-oss's bnb path, which maps float16 to bfloat16 on purpose (loader.py:1662). that part is a code read, gpt-oss wasn't run.

it's 3405f7e + 16fafa1 (the second one fixes the attention-dtype test fixture for the new branch) on the mirror (LeoBorcherding#83), with a GPU test that fails at 05236b9 and passes with the change. happy to push both here. the PR's 17 tests are decision tables and source-string checks, so none of them catch the P1.

still true from last time: with zoo 1316 in, this PR alone changes nothing I can measure. not run: RX 5700 XT, T4/V100, Linux ROCm, QLoRA, gpt-oss, no bf16 control card.

@LeoBorcherding

LeoBorcherding commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

reran this at the real SHAs this time (worktrees at 004351b and 05236b9, not the overlay from my first comment), on the RX 6500 XT (gfx1034), windows 11, torch 2.11.0+rocm7.13.0, unsloth_zoo 2026.9.8. short version: it's harmless and it trains, but with today's zoo it doesn't change anything I can measure, and the float32 never reaches the load.

RX 6500 XT gfx1034, dtype=torch.float16    # 004351b (base)                  # 05236b9 (this PR)
Qwen3.5-0.8B dtype into from_pretrained     torch.bfloat16                     torch.bfloat16
  final weights                             fp16 852.9M, fp32 0.1M             fp16 852.9M, fp32 0.1M
  GC buffer dtype                           bfloat16                           float32
  3 SFT steps, 16-bit LoRA                  0.0366659239 0.0366659239          0.0366659239 0.0366659239
                                            0.0281325746                       0.0281325746
gemma-3-270m-it dtype into from_pretrained  torch.bfloat16                     torch.bfloat16
  forward logits                            0 nan, 0 inf                       0 nan, 0 inf

base trains now because zoo 1316 and 1419 are in, so the LLVM abort this PR was written for doesn't happen at 004351b anymore.

the one thing to look at is the Codex P1. it's real: vision.py:1415-1417 still does torch_dtype = torch.bfloat16 under do_forced_float32, so the card gets bf16 weights until zoo's forced-float32 pass casts them to fp16. but switching that line to float32 isn't the fix. zoo only converts bf16 leftovers, so a float32 load leaves the weights split (183.4M fp32, 669.6M fp16) and Qwen3.5 dies with Half != float in Qwen3_5GatedDeltaNet_forward. it also doubles load VRAM. what does work is staging in float16 when the device has no bf16:

         if do_forced_float32:
-            torch_dtype = torch.bfloat16
+            if SUPPORTS_BFLOAT16 or dtype == torch.bfloat16:
+                torch_dtype = torch.bfloat16
+            else:
+                torch_dtype = torch.float16

on the same card that gives dtype=torch.float16 into from_pretrained, gemma-3-270m weights bit-identical to this PR's head, and Qwen3.5 trains 3/3 (0.0367048420 0.0367048420 0.0281461794). the small shift there is the 18 linear_attn.norm.weight tensors, which the checkpoint stores fp32: fp16 staging lands 8x closer to them than bf16 does. the dtype == torch.bfloat16 half keeps gpt-oss's bnb path, which asks for bf16 on purpose, where it is. I've got it with a GPU test that fails at 05236b9 and passes with the change, it's 3405f7e on the mirror, with c0608b0 gating that test on a CUDA probe the repo's GPU spoof can't flip (LeoBorcherding#83), happy to push it here if you want it.

also, the 17 tests in the PR are decision tables and source-string checks, so none of them would have caught the P1.

not run: RX 5700 XT (gfx1010, no torch on this box that can run a kernel on it), T4/V100, Linux ROCm, QLoRA, gpt-oss, and no bf16 card as a control.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants