Skip to content

Studio FLUX.3: keep bf16 weights as stored on fp16-only GPUs and compute in float32 per layer - #17173

Merged
danielhanchen merged 2 commits into
mainfrom
fix/flux3-fp16-card-manual-cast
Nov 9, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
fix/flux3-fp16-card-manual-cast

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Summary

FLUX.3 renders black in float16, so since #17124 fp16-only GPUs (T4 and other Turing cards) run it in float32. The float32 path widened every bf16 weight on the host: Flux3Transformer2DModel.from_pretrained(torch_dtype=float32) and the Qwen3-VL encoder both materialise float32 copies, about 40 GB for klein. On a Kaggle T4 (31 GB host RAM) the dense klein and klein-base loads are killed before the first step, for Off and for any other dense request, run alone on the VM.

This PR keeps the checkpoint's bf16 weights as stored and upcasts each layer's weight to float32 at call time ("manual cast"), which is what the baseline stack does on these cards (it stores the DiT in bf16 and runs a float32 manual cast when bf16 compute is unavailable). Host RAM, VRAM and every offloaded transfer stay at bf16 size while every matmul still runs in float32. Upcasting bf16 to float32 is exact, so the math is the same as the float32 load.

  • diffusion_manual_cast.py: apply_manual_cast_(module, compute_dtype) swaps every plain nn.Linear / nn.Embedding stored in bf16 / fp16 for a twin whose forward upcasts the weight (and bias) to the compute dtype, and converts every other half tensor (norms, small embedders, the owner of the first floating parameter so module.dtype still answers float32) up front. Quantised, GGUF and other nn.Linear subclasses are left alone. The forward is plain F.linear on a casted weight, so it composes with group offload, LoRA wrapping and torch.compile (traced with fullgraph=True in the tests).
  • diffusion_flux3.py: flux3_storage_dtype(target, dtype) is bf16 only for a CUDA float32 load (the promoted fp16-only case). load_flux3_pipeline then loads the text encoder and the transformer at bf16 and applies the manual cast, but only when the safetensors headers show every float tensor of that component is stored as bf16 (else today's widened load, since loading wider data at bf16 would round it). An explicit or native transformer quant keeps the widened transformer, because its quantiser rebuilds the dense Linears it reads.
  • All three FLUX.3 load sites (dense pipeline, single file / GGUF, assembled pipe) pass the storage dtype; on the GGUF path this is the text encoder only.
  • diffusion_speed._fuse_qkv skips a manual-cast denoiser: a fused to_qkv would be a plain bf16 Linear fed float32 activations.

bf16 GPUs (they load FLUX.3 at bf16), CPU, MPS and XPU are unchanged: flux3_storage_dtype answers None for every non-float32 or non-CUDA load. Kill switch: UNSLOTH_STUDIO_MANUAL_CAST=0 restores the widened float32 load.

Results (Kaggle T4, 31 GB host, 1024x1024, fresh process per arm, same seeds and prompts, one arm at a time on the VM)

Base = main at the merge base, head = this branch.

model arm loads s / image peak VRAM process tree PSS image
klein, dense (16 steps) base no, killed at 1220 s - - - -
klein, dense head, run 1 yes 206.5 11.46 GiB 25.0 GiB finite
klein, dense head, run 2 yes 206.0 11.46 GiB 24.6 GiB finite
klein-base, dense (50 steps, CFG 3.5) base no, killed at 1162 s - - - -
klein-base, dense head, run 1 yes 1195.2 9.68 GiB 25.3 GiB finite
klein-base, dense head, run 2 yes 1196.7 9.68 GiB 25.3 GiB LPIPS 0.000 vs run 1
klein, GGUF Q8_0 base, run 1 / run 2 yes 241.6 / 241.4 11.01 GiB 26.5 / 27.0 GiB (RSS 46.7 / 27.5) LPIPS 0.000 run 2 vs run 1
klein, GGUF Q8_0 head, run 1 / run 2 yes 228.7 / 240.4 10.29 GiB 20.2 / 20.8 GiB (RSS 20.7 / 20.8) LPIPS 0.000 vs base (pixel-identical)
klein, dense the baseline stack, bf16 weights, float32 manual cast yes 203.5 14.99 GiB 15.0 GiB finite

Quality: the T4 dense head render (float32 per layer) against a bf16 Studio render of the same prompts and seeds on an L4 is LPIPS 0.013 mean / 0.017 max (3 prompts), the GGUF Q8_0 render 0.014 / 0.020 on both base and head, and head run 2 against run 1 is 0.000. No image is black (per-image pixel means 49 to 157). Speed of the dense head is within 1.5% of the baseline stack on the same VM (206.0 vs 203.5 s / image) at 3.5 GiB less VRAM. GGUF speed is unchanged within noise; its peak host RSS drops from 46.7 / 27.5 GiB to 20.7 / 20.8 GiB because the text encoder is no longer widened.

On head the load log shows the cast engaged on both components (text_encoder keeps 8.99 GiB of bfloat16 weights as stored and computes in float32, transformer keeps 10.33 GiB ...); the transformer streams with 4.7 GiB resident instead of being priced and moved at float32 size.

Does only part of the model need float32?

Measured on the same T4: the text encoder in float32 (manual cast) with the transformer in float16 still renders black (pixel mean 0.0, all three prompts, two runs), so the transformer's residual stream needs float32 as well, not just the encoder. The NaN probe from that run saw the encoder's first decoder layer go non-finite in float16, and a float16 DiT Linear peak of 56448, near the float16 limit. Both components therefore keep float32 compute.

Tests

studio/backend/tests/test_diffusion_flux3_manual_cast.py (CPU, tiny random models):

  • A tiny Flux3Transformer2DModel and a tiny Qwen3VLForConditionalGeneration stored in bf16 with the manual cast give outputs bit-identical (torch.equal) to the same weights loaded in float32, module.dtype answers float32, every remaining Linear weight is bf16.
  • The manual-cast Linear traces with torch.compile(fullgraph=True); subclassed Linears are left alone.
  • flux3_storage_dtype is bf16 only for CUDA float32 loads and honours the kill switch.
  • The stored-dtype check: all-bf16 shards take the cast, any F32 / F16 tensor or missing files keep the widened load.
  • Every load_flux3_pipeline call site passes the storage dtype, and the dense site keeps a quantised transformer widened.
  • _fuse_qkv skips a manual-cast denoiser.

These fail on main (the module does not exist) and pass here. The FLUX.3, FLUX.3 encoder prequant and QKV-drop suites pass unchanged.

Not covered

@danielhanchen danielhanchen self-assigned this Nov 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-08T22:40:18.865153Z 8d852f2 Manual request
ℹ️ 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 8d852f2aa8

ℹ️ 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".

@danielhanchen
danielhanchen merged commit f81dad0 into main Nov 9, 2026
@danielhanchen
danielhanchen deleted the fix/flux3-fp16-card-manual-cast branch November 9, 2026 00:28
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 9, 2026
…pe and out of the bf16 fold (unslothai#17201)

## What happened

unslothai#17173 loads FLUX.3 on fp16-only cards (T4 and other pre-Ampere GPUs)
with bf16 weight storage and float32 compute per layer: each plain
`Linear` becomes a manual-cast twin that upcasts its weight per call.
That covers the base GEMMs, but not LoRA:

- PEFT places every injected adapter at its base layer's weight dtype
(`_move_adapter_to_device_of_base_layer`). On a manual-cast layer that
is the stored bf16, so `lora_A` / `lora_B` were bf16, PEFT cast the
activation down to bf16, and both adapter GEMMs ran in bf16 on exactly
the cards that have no native bf16. fp32 adapter files were also rounded
through bf16 on load.
- The LoRA fold (`diffusion_lora_fuse`) computes the update in fp32 and
rounds the merged weight back to the weight dtype. With bf16 storage,
small updates that the former fp32 storage kept are rounded away (a
weight of 1.0 plus an update of 1/1024 stayed 1.0), and the layer is
then marked merged so the adapter no longer runs separately.

## What this changes

- On a manual-cast base layer, adapters are placed at the layer's
compute dtype (float32) instead of its storage dtype. This hooks PEFT's
adapter placement, so it applies before the state dict is copied in
(fp32 file values are kept exactly) and on PEFT's `low_cpu_mem_usage`
path. Every other layer keeps PEFT's own placement.
- The fold plan declines manual-cast layers, so those LoRAs stay unfused
and exact rather than folded lossily into bf16.
- `UNSLOTH_STUDIO_MANUAL_CAST_LORA=0` restores the previous adapter
placement and fold.

Base storage is unchanged: the bf16 weights stay bf16, so the host and
VRAM savings from unslothai#17173 hold. The adapters add only their own fp32
bytes.

## Evidence

CPU, tiny 3-layer model (bf16 storage + manual cast, PEFT 0.19.1
injection, the same path diffusers `load_lora_adapter` takes),
`tests/test_diffusion_manual_cast_lora.py`:

| | main | this PR |
|---|---|---|
| adapter dtype | bf16 | fp32 |
| adapter values vs file (fp32) | rounded | exact |
| GEMM dtypes in forward | fp32 base, bf16 adapter | all fp32 |
| output vs fp32-stored reference | differs | equal (1e-6) |
| fold on manual-cast layers | folds into bf16 | declined |

On main, 3 of the 6 new tests fail
(`test_adapter_keeps_fp32_values_and_gemms[False]`, `[True]`,
`test_fuse_declines_manual_cast_layers`); on this branch all 6 pass. The
kill switch test and a plain bf16 model (no manual cast) keep the
previous behavior on both.

Tesla T4 (sm 7.5, torch 2.14.1, diffusers 0.42.1, PEFT 0.19.1), random
tiny-config FLUX.3 transformer (hidden 1536, 2 + 4 blocks, 1024 image +
128 text tokens), rank 32 LoRA on every block Linear, loaded with
`load_lora_adapter`. Same card and process for every arm, 3 x 10
forwards each:

| arm | adapter dtype | GEMM dtypes | max abs diff vs fp32 storage | ms
/ forward (median) |
|---|---|---|---|---|
| fp32 storage (before unslothai#17173) | fp32 | 108 fp32 | 0 | 153.1 |
| main (manual cast) | bf16 | 60 fp32, 48 bf16 | 5.3e-05 | 166.6 (repeat
170.2) |
| this PR | fp32 | 108 fp32 | 0.0 (bit-equal) | 165.0 |

The T4 renders finite output on main as well, and the timing difference
sits inside the main-vs-main repeat spread, so this is a precision fix
rather than a speed fix: with the change, LoRA output on manual cast is
bit-equal to the fp32-stored model, and adapter memory is the only extra
cost (0.88 to 0.91 GB peak here, against 1.58 GB for fp32 storage).

`torch.compile(fullgraph=True)` over a manual-cast model with an fp32
adapter: 0 graph breaks, 1 graph, no recompiles (same as main).

Existing tests `test_diffusion_flux3_manual_cast.py`,
`test_diffusion_lora_fuse.py`, `test_diffusion_lora_files.py`,
`test_diffusion_lora.py`, `test_diffusion_lora_incremental_remerge.py`,
`test_diffusion_lora_quant_merge.py`: same results as main (the four
`moss` loader failures in `test_diffusion_lora_files.py` /
`test_diffusion_lora.py` fail on main too).
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 9, 2026
…he bf16 checkpoint as stored instead of widening the transformer to float32 (unslothai#17228)

## Summary

unslothai#17173 keeps FLUX.3's bf16 weights as stored on fp16-only GPUs (T4) and
upcasts per layer, but an explicit transformer quant still loads the
transformer widened to float32 first ("a transformer quant rebuilds the
dense Linears it reads"). For the fp16-only card's native build (INT8
from unslothai#17167, FP8 from unslothai#17218) that widened copy is not needed: the
native linear reads `weight.float()` anyway, and widening bf16 to
float32 is exact, so the codes are the same either way. The widened load
costs host RAM on the 31 GB Kaggle T4 VM, where a Studio INT8 load
already sits at 23 GiB PSS.

This PR loads the transformer at bf16 with the manual cast when the
requested scheme takes the fp16-only card's native route, and lets that
build read manual-cast Linears:

- `load_flux3_pipeline(..., transformer_storage=...)` is also true for a
native scheme on an `fp16_card_int8_host` that is not the shared ROCm /
MPS native route (`native_quant_scheme(...) is None`) and not the native
offload build.
- `make_filter_fn(require_dtype=...)` counts a manual-cast Linear by its
compute dtype (`linear_compute_dtype`: `_unsloth_compute_dtype`, else
the weight dtype), so the float32 filter of the fp16-card path still
selects them.
- The native linear takes its compute dtype from that attribute too, and
holds a manual-cast source's bf16 bias at the compute dtype (`F.linear`
needs one dtype).
- Everything the quant skips (the M=1 modulation projections, small
layers) stays a bf16 manual-cast Linear instead of a float32 copy.

bf16 GPUs, explicit-quant loads elsewhere, ROCm / MPS native routes and
the native offload build are unchanged. Kill switch:
`UNSLOTH_DIFFUSION_FP16_CARD_QUANT_STORAGE=0` restores the widened load.

## Results (Kaggle T4, 31 GB host, FLUX.3 klein, 1024x1024, 16 steps,
fresh process per arm, one process on the VM, same seeds)

Both arms carry unslothai#17217 (INT8 renders), unslothai#17218 (FP8 on Turing) and the
other T4 FLUX.3 PRs of this round; head adds this PR. Order head-less,
head, head, head-less.

| format | arm | s / image (2 runs) | load s | process tree PSS | min
MemAvailable | peak VRAM | LPIPS |
|---|---|---|---|---|---|---|---|
| INT8 | widened (today) | 52.8 / 52.9 | 145.7 / 143.6 | 23.1 / 23.0 GiB
| 8.0 / 8.0 GiB | 11.34 GiB | - |
| INT8 | head (stored bf16) | 53.1 / 53.2 | 136.0 / 133.7 | 20.9 / 21.2
GiB | 12.9 / 12.9 GiB | 11.20 GiB | 0.000 vs widened (pixel-identical),
both runs |
| FP8 | widened (today) | 185.2 | 121.9 | 22.0 GiB | 8.3 GiB | 11.05 GiB
| - |
| FP8 | head (stored bf16) | 185.8 | 113.9 | 21.1 GiB | 12.7 GiB | 11.19
GiB | 0.000 vs widened (pixel-identical) |

Same images and the same speed; 0.9 to 2.2 GiB less process PSS, 4.4 to
4.9 GiB more host memory left free at the low point of the load, and an
8 to 10 s shorter load.

## Tests

`studio/backend/tests/test_diffusion_fp16_card_quant_storage.py` (tiny
diffusers `Flux3Transformer2DModel`, Turing capability monkeypatched):
- INT8 (and FP8 where unslothai#17218 is present) built from the manual-cast bf16
transformer gives the same native layers as the widened float32 load:
same layer set, compute dtype float32, `torch.equal` codes, scales and
biases; the rest stay bf16 manual-cast Linears; the forward output is
`torch.equal` to the widened model's.
- The filter counts a manual-cast Linear by its compute dtype; a plain
bf16 Linear is still rejected by the float32 filter.
- The loader gate is the fp16-card native route only; the kill switch
and its name.

The INT8 case fails on `main` (no layer passes the float32 filter). The
fp16-card INT8, FLUX.3 manual cast, native quant, fused native quant and
FLUX.3 suites pass unchanged (407 passed, diffusers 0.42.1).

## Not covered

- Without unslothai#17217, INT8 still fails its first render on a T4 (separate
fix); without unslothai#17218, FP8 is still refused there.
- Other Turing cards were not run.
- The regression switchboard GPU units did not run (its batch notebook
is over Kaggle's size cap); owed.
bestoffersdirect-fork-sync Bot pushed a commit to BestOffersDirect/unsloth that referenced this pull request Nov 9, 2026
…d of refusing it (unslothai#17218)

## Summary

On a T4 (and every other Turing GPU, sm75) Studio refuses
`transformer_quant="fp8"` before the load:

```
transformer_quant='fp8' could not be used: this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16).
```

The baseline stack runs FP8 on the same card: it keeps the fp8 weights
and upcasts each layer to the compute dtype at call time (a T4 has no
fp8 matmul). unslothai#17167 opened the same refusal for INT8 by routing it to
Studio's torchao-free native linear. This PR does the same for FP8,
weight-only:

- `fp16_card_fp8_scheme(target, requested, family)`: `fp8` for an
explicit fp8 request on an `fp16_card_int8_host` (CUDA, NVIDIA, not the
torchao stub, pipeline dtype float16 or float32, compute capability in
[7.5, 8.0)), honouring the family deny list. AUTO, int8, mxfp8 and nvfp4
are unchanged.
- `fp16_card_native_scheme` / `fp16_card_native_host` answer for both
explicit int8 and fp8; the image precision gate and the loader's
`native_scheme` read them in place of the int8-only helpers.
- `quantize_transformer` builds native fp8 linears (per-row e4m3 codes,
float32 scales) in the pipeline dtype, weight-only (`act_int8` stays
False for fp8). The forward is `F.linear` on the upcast weight, so a
float32 FLUX.3 load computes every matmul in float32 as before.
- `native_quant_scheme` and `select_transformer_quant_scheme` are
untouched, so the hosted fp8 prequant planners and the ROCm / MPS native
routes keep their answers.

Kill switch: `UNSLOTH_DIFFUSION_FP16_CARD_FP8=0` restores the refusal
(`UNSLOTH_DIFFUSION_FP16_CARD_INT8=0` also closes it, since both ride
the same Turing host check).

## Results (Kaggle T4, 31 GB host, FLUX.3 klein, 1024x1024, 16 steps,
fresh process per arm, same VM, same seeds)

Base = `main` at the merge base `dcb1eb1ec7`, head = this branch. The
baseline stack ran an fp8 file of the same linear set (per-tensor e4m3
weights, float32 manual cast) on the same VM.

| arm | output | s / image (2 renders) | peak VRAM | process tree PSS |
LPIPS vs own float32 dense |
|---|---|---|---|---|---|
| base, FP8 | refused (message above) | - | - | - | - |
| head, FP8 (weight-only, float32 compute) | image | 206.2 (206.0 /
206.5) | 11.15 GiB | 22.8 GiB | 0.038 (max 0.068) |
| baseline stack, fp8 file, float32 manual cast | image | 201.6 (202.2 /
201.1) | 10.99 GiB | 5.2 GiB | 0.037 (max 0.056) |

Earlier the same day on another T4 VM the baseline fp8 arm took 212.2 /
210.5 s (A/A), so the head sits inside the baseline's own VM-to-VM
spread: both run every matmul in float32 on this card, the fp8 weights
only save memory. LPIPS is against each stack's own float32 dense render
of the same 2 prompts and seeds (Studio's is bit-identical across the
VMs used). Host PSS is higher on Studio because an explicit quant on a
float32 load still widens the transformer before quantising it (as INT8
does today, unslothai#17173); not changed here.

## Tests

`studio/backend/tests/test_diffusion_fp16_card_fp8.py` (CPU, capability
monkeypatched):
- Turing fp16 / fp32 pipelines take fp8; AUTO, none, int8 (its own
route) and mxfp8 do not.
- Every other capability (sm61, sm70, sm80, sm86, sm89, sm90, sm100,
sm120, unknown) x every dtype is unchanged, as are bf16 on Turing and
CPU / MPS / XPU; the shared native route and the torchao selector are
not widened.
- Both kill switches, the family deny list, and the switch name.
- `quantize_transformer` builds weight-only native fp8 linears in the
pipeline dtype (fp16 and fp32), output within 5% of the dense layer;
Ampere fp16 still declines.
- The image precision gate admits fp8 for FLUX.3 (float32 and float16
targets) and Qwen-Image-2.1 on Turing, with and without `low_vram`, and
refuses it with the kill switch or on sm70 / sm86.

`test_diffusion_fp16_card_int8.py`: the "other schemes still refused"
case now lists mxfp8 only (fp8 is the point of this PR). The int8
native, transformer quant and pipeline prequant suites pass unchanged,
except
`test_unpinned_torchao_host_copy_is_a_distinct_wrapper_over_the_same_data`,
which fails the same way on `main` in this environment (torchao build).

## Not covered

- Other Turing cards (RTX 20xx, Quadro RTX) take the same path but were
not run.
- The regression switchboard GPU units did not run (its batch notebook
is over Kaggle's size cap); owed.
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.

1 participant