Skip to content

Studio Z-Image fp16 training: scaled fp16 GEMMs instead of fp32 islands on T4 (1.7x per step) - #19057

Merged
danielhanchen merged 8 commits into
mainfrom
studio-zimage-t4-fp16-islands
Nov 23, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-zimage-t4-fp16-islands

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Z-Image LoRA training on a T4 (fp16 path from #18355) spent about half of every step in fp32 volta_sgemm: attention.to_out.0 and feed_forward.w2 run as fp32 islands in all 34 blocks because their activations pass the fp16 range. This PR keeps those islands but runs their nf4 matmul on fp16 tensor cores with fp32 accumulate and fp32 output. A power-of-two input scale keeps the fp16 operand in range, so nothing can overflow.

Colab T4, Z-Image-Turbo, nf4, 512 px, rank 16, gradient checkpointing, 300 steps, 3 seeds each:

s/step (median) peak skipped steps
main 6.62, 6.64, 6.60 11.51 to 11.52 GB 0
this PR 3.88, 3.89, 3.87 11.46 GB 0

That is 1.71x faster per step (-41%). At 1024 px (5 steps, so only a rough speed): 18.6 vs 26.1 s/step, peak 11.20 vs 11.09 GB. The checkpointing budget fills the card to about the same level in both, so the peak is that budget, not a floor.

What overflows (measured on the T4)

Max over 5 real training steps, all 34 blocks:

module max abs input max abs output max abs grad out modules past 65504
to_out.0 1.7e3 1.4e5 17 output: 2 of 34
w2 2.3e5 8.7e5 143 input: 1 of 34 (layers.0), output: 14 of 34
w1 (fp16, reference) 56 481 939 none
  • The forward activations overflow, not the grads: with the GradScaler at 65536 the largest grad is 1.5e3.
  • w2's input is fp32 (the LoRA wrapper returns fp32 for w1 / w3), so silu(w1) * w3 reaches 2.3e5 before the island.
  • The weights stay well inside fp16 range (max 2.7). They are not exact in fp16, though: see "Weight precision" below.

How

diffusion_dit_fp16.py:

  • New table FP16_SCALED_MM_MODULES (Z-Image to_out.0 and w2 only). The island still turns autocast off and runs the LoRA branch in fp32. Only the nf4 base matmul changes.
  • Forward: scale the input by a power of two so its amax lands in (2^14, 2^15], split it into fp16 high and low parts, run one fp16 GEMM with fp32 output (torch.mm(out_dtype=torch.float32)), then undo the scale. The split keeps about 22 mantissa bits of the input. Both parts are written straight into the fp16 buffer, with no fp32 copy of the input.
  • The scale exponent is bounded at +/-113, so every finite fp32 amax (up to fp32 max) lands at or under 2^15.
  • Input grad: the same scaled GEMM with one fp16 term.
  • The nf4 weight is dequantised straight to fp16 (one rounding of the exact value).
  • inf or nan inputs stay non-finite, so the GradScaler still skips those steps.
  • Falls back to the fp32 island when torch.mm has no out_dtype, on GPUs below sm70, for a weight past the fp16 range, or with UNSLOTH_STUDIO_DIT_FP16_SCALED_MM=0. The support probe runs per device (cuda:N), on the card the nf4 weights live on. A CUDA out-of-memory during the probe or the install check propagates instead of being cached as "unsupported".
  • model_load_completed reports fp16_scaled_mm (layers installed, 68 on Z-Image). At the end of the run, fast_lora_stats (or fp16_stats without fast LoRA) adds fp16_scaled_mm_calls, the scaled GEMM forwards actually taken. On the T4 that is about 94 per step.

klein and Wan 2.2 5B are unchanged: their island tables have no scaled entries (fp16_scaled_mm: 0).

Weight precision

dequantize_4bit returns the quant state's dtype, which is bf16 on Z-Image. bitsandbytes' own fp32 forward (the fp32 island on main) dequantises straight to fp32. Until the last commit the scaled GEMM used the bf16 copy, so its weights carried 8 mantissa bits. It now asks for fp16 directly.

Real nf4 w2 (10240 to 3840) under a PEFT LoRA on a T4, inputs up to 2.3e5, rel-L2:

bf16 dequant (before) fp16 dequant (this PR)
weights vs exact nf4 values 1.6e-3 2.1e-4
forward vs the fp32 island 1.5e-3 2.0e-4
input grad vs exact weights 1.6e-3 2.9e-4
GEMM vs fp32 on the same weights, forward 1.6e-5 1.6e-5
GEMM vs fp32 on the same weights, input grad 2.1e-4 2.1e-4

The fp32 island's own input grad also dequantises to bf16 (1.6e-3 from exact). Same speed: 3.83 s/step over 40 steps, with all 68 layers installed and about 95 scaled GEMM calls per step.

GEMM accuracy and speed on captured tensors

Real Z-Image inputs and grads from training, T4, error vs an fp64 matmul on the same weights (rel-L2), CUDA-event median. These numbers predate the last commit. They measure the GEMM on fixed fp16 weights, which that commit did not change:

GEMM (1056 tokens) fp32 island fp16 one term fp16 hi + lo (this PR)
w2 forward error 0.5e-6 to 2e-6 4.5e-5 to 1.4e-4 5e-6 to 2.3e-5
w2 forward time 29 ms 5.5 to 6.2 ms 8.3 to 9.4 ms
w2 input-grad error 0.6e-6 to 0.7e-6 1.4e-4 to 2.0e-4 (one term)
w2 input-grad time 25 ms 4.7 ms (one term)
to_out forward time 7.8 ms 1.6 ms 3.0 ms

Every other nf4 linear in the step already runs fp16 in and out: w1 measures 2.1e-4 to 2.5e-4 on the same data.

Profile, 2 steps: GEMM time 4.05 s to 1.56 s per step, elementwise 1.15 s to 1.35 s.

Accuracy

LoRA grads vs an all-fp32 reference

Same seed and data, step 1. The reference runs every block as an fp32 island. Aggregate rel-L2 over all LoRA grads, median of the per-parameter rel-L2, and the worst parameter:

aggregate median per parameter worst parameter
main A/A (two main runs) 0.05% 0.0% 0.13%
main 0.99% 0.11% 4.2% (noise_refiner.0.feed_forward.w3.lora_B)
this PR before the fp16 dequant 1.49% 0.26% 5.4% (layers.15.attention.to_k.lora_B)
this PR 1.29% 0.12% 5.7% (noise_refiner.0.feed_forward.w3.lora_B)
fp16 one term, bf16 weights 2.34% 0.26% 8.5%
  • Steps 2 and 3, same reference: main 10.8% and 1.46%, this PR 12.5% and 1.27% (median per parameter 0.10% / 2.8% vs 0.13% / 2.6%). Before the fp16 dequant: 53% and 2.8%.
  • Step 2 amplifies any change: Adam's first update is close to sign(g), so near-zero grads that flip sign change the weights.

Short runs (40 steps)

Measured before the last two commits, same seed and data, fresh process per arm, base and head interleaved on one T4:

main A/A this PR vs main
per-step loss, median relative difference 0.7e-4 to 1.6e-4 4.2e-4 to 4.8e-4
mean loss, steps 1-40 0.36307 to 0.36334 (4 runs) 0.36304, 0.36307
mean loss, steps 21-40 0.31547 to 0.31601 (4 runs) 0.31550, 0.31558
sample LPIPS after 40 steps 0.0013, 0.0014 0.0013 to 0.0021
sample LPIPS before training 0.0 0.0014

Training quality after 300 steps

Z-Image-Turbo is a few-step distilled model, so LPIPS against main's samples says little about quality. The adapters were trained on the head before the fp16 dequant commit, which is the less accurate variant, then scored on one common inference path (main's fp32 islands), so arms differ only in their adapter. 3 seeds each, 8 training images.

Held-out denoising loss: 4 images from the same 3dicon set that are not in the training set, 6 fixed sigmas (0.15 to 0.9), 2 fixed noise draws each:

seed main this PR difference
0 0.28690 0.28739 +0.00050
1 0.28562 0.28570 +0.00008
2 0.28696 0.28706 +0.00010
no LoRA 0.39001

Main's seed-to-seed spread is 0.00134. The mean difference (+0.00022) is 0.17x of it.

Text alignment and preference: 10 prompts (4 of the sample prompts plus 6 new 3dicon prompts), one fixed noise per prompt, 8-step Euler. CLIP-T is openai/clip-vit-large-patch14, 100 x cosine; PickScore is yuvalkirstain/PickScore_v1. Both score against the prompt without the trigger words:

main, per seed this PR, per seed mean difference main seed-to-seed range
PickScore 21.54, 22.10, 22.06 21.46, 22.16, 22.02 -0.02 0.57
CLIP-T 29.97, 30.20, 29.73 27.82, 30.85, 29.49 -0.58 0.46
  • Per prompt, the PR vs main on the same seed is closer than main vs main across seeds. PickScore median abs difference 0.13 vs 0.31; CLIP-T 0.92 vs 1.35.
  • PickScore: the mean difference is 0.04x of main's seed-to-seed range; paired t over prompts is -0.27.
  • CLIP-T: seeds 1 and 2 sit inside main's range. Seed 0 is lower (-2.15), mostly on two prompts, so the mean difference (-0.58) is just outside main's per-seed range (0.46); paired t over prompts is -1.74, which is not significant.

Seed 0 run again on the same VM: main with the same seed and code (the backward is not bit-reproducible, so two main runs drift apart), and this PR with the fp16 dequant commit. Same eval; the no-LoRA scores repeat to the last digit, so the eval is deterministic:

seed 0 main main again this PR before the fp16 dequant this PR
held-out loss 0.28690 0.28742 0.28739 0.28720
CLIP-T 29.97 29.33 27.82 29.45
PickScore 21.54 21.83 21.46 21.84
s/step 6.62 6.71 3.88 3.86
  • Main against itself on seed 0 moves CLIP-T by 0.64 on the mean and 1.79 per prompt, and held-out loss by 0.00052.
  • This PR lands between the two main runs on held-out loss and CLIP-T, and within 0.01 of "main again" on PickScore. Per prompt it is 0.62 (CLIP-T) and 0.20 (PickScore) from "main again".
  • The earlier head's seed-0 CLIP-T (-2.15) is outside that run-to-run drift. Against the spread of all four main runs (CLIP-T 29.33 to 30.20, range 0.87), its 3-seed mean difference of -0.42 is inside.
  • 68 scaled layers and 28240 scaled GEMM calls in 300 steps (94 per step), 0 skipped steps.

Cross-seed check (300 steps, earlier run)

Same T4 VM, fresh process per arm, interleaved base s0, head s0, base s1, head s1, base s2, head s2; 300 steps each; sampler noise pinned so every seed renders from the same noise. Measured on b6f05c2. The T4 path is unchanged from there to the commit before the fp16 dequant: the step-1 model output on a fixed batch is bit-identical. LoRA grads differ by 5.6e-4, the same as two runs of the same code (5.5e-4; the backward is not bit-reproducible).

seed main, mean loss steps 201-300 this PR difference
0 0.23995 0.23878 -0.00118
1 0.23813 0.23793 -0.00020
2 0.23414 0.23450 +0.00036
  • Main's seed-to-seed spread is 0.0058; every head value sits inside it.
  • Samples after 300 steps (4 prompts, 12 of 12 pairs): head vs main on the same seed is mean LPIPS 0.037 (0.0012 to 0.174); main vs main across seeds is 0.101 (0.030 to 0.358). One of the 12 images (seed 2, prompt 2) was missing from the earlier table because the executed notebook dropped its output line. It was recovered from the run's streamed log (LPIPS 0.0012).
  • The repeat run above (seeds 0, 1, 2) gives main 0.23935 / 0.23817 / 0.23442 and head 0.23963 / 0.23770 / 0.23425 for the same window.

Final head on a T4

Colab T4, Studio installed at the final head, main = the same install with this diff reversed, 40 Z-Image LoRA steps (nf4, 512px, rank 16, gradient checkpointing, seed 0), fresh process per run, interleaved:

run scaled layers scaled calls skipped steps s/step step-40 loss peak
main, run 1 - - 0 6.32 0.3366 11.52 GB
main, run 2 - - 0 6.33 0.3365 11.52 GB
this PR, run 1 68 3800 0 3.63 0.3373 11.47 GB
this PR, run 2 68 3800 0 3.31 0.3374 11.47 GB
this PR, Q/K/V-only adapter 68 3176 0 3.00 0.4348 11.71 GB

The mean loss over the last 20 steps is 0.3154 here against 0.3158 on main, and the loss scale stays at 65536 throughout. The Q/K/V-only run leaves to_out.0 and w2 without an adapter, so the islands wrap the bare nf4 linears: the scaled path still runs and nothing overflows (its loss is a different adapter's, not comparable). test_diffusion_dit_fp16_t4.py on the same T4: 71 passed, including the CUDA test against the fp32 island.

GTX 16xx cards (sm75 without tensor cores) now keep the fp32 islands.

Tests

studio/backend/tests/test_diffusion_dit_fp16_t4.py, all CPU unless noted (all new ones fail on main):

  • install on to_out.0 / w2 only, and the kill switch installs nothing
  • finite past fp16 range, matching fp32 in the forward and in the input grad
  • the split keeps fp32-level input precision, and the in-buffer split equals the old fp32-copy split (200-case sweep, 1e-30 to 1e30, zeros, -0, nan)
  • power-of-two scale bounds, including amax 1e30, fp32 max and tiny values
  • non-finite inputs stay non-finite
  • fallback for a weight past fp16, pre-sm70 GPUs and torch.mm without out_dtype
  • per-device probe cache, probe on the weights' card, OOM propagates and is not cached (probe and install)
  • runtime call counter, and the trainer's load and end-of-run reports (behavioural, replacing a source-text check)
  • dequant asks bitsandbytes for fp16 directly
  • gradient checkpointing recompute
  • CUDA: a real bitsandbytes nf4 w2 (10240 to 3840) under PEFT. It checks that 1 layer is installed, the probe returns True on sm75, and one call is counted. It also checks the GEMM against fp32 on its own weights, end to end against the fp32 island within the weight rounding, and the input grad closer to exact than the island's own. It passed on the Colab T4 (70 passed there).

The fp16, fast LoRA, frozen int8, int8 dequant cache, DiT trainer and LoRA trainer suites: 501 passed, 1 skipped (the CUDA test, no local GPU).

Not covered

  • 300 steps on 8 images at 512 px. 1024 px only for 5 steps (peak and a rough speed). No gradient accumulation, no resume.
  • The 300-step quality runs used the head before the fp16 dequant commit, except one seed-0 run of the final head. The final head has no 3-seed run.
  • Only a Colab T4 (sm75). Other non-bf16 cards and torch builds without mm(out_dtype=) take the fp32 fallback, which has only CPU tests. The per-device probe has only CPU tests with mocked devices.
  • klein and Wan regression runs are short (20 and 12 steps). Their code path is unchanged.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-23T21:05:36.614132Z 6b549ae 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: b6f05c2cea

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

…hrough, runtime call count

- scaled_mm_supported takes a device (cuda, cuda:N, torch.device) and caches per (type, index); the
  probe reads that card's capability and runs on it. install_fp32_islands probes the card the routed
  nf4 weights live on.
- A CUDA OOM in the probe or the install-time dequant propagates instead of being cached as unsupported.
- Power-of-two scale exponent bounded at 113 so every finite fp32 amax lands at or under 2^15.
- Count the scaled GEMM forwards actually taken; the trainer reports fp16_scaled_mm_calls next to
  fp16_scaled_mm at the end of the run (fast_lora_stats, or fp16_stats without fast LoRA).
- The split forward forms hi / lo in-kernel without an fp32 copy of the input (same values).
- Tests: real-probe kill switch, per-device / OOM probe, runtime counter, behavioural trainer report,
  pow2 extremes, split equality sweep, and a CUDA test on a real bitsandbytes nf4 layer under PEFT.
…2 on its own weights

On a T4 the GEMM lands at 1.6e-5 (forward) and 2.1e-4 (dx) from an fp32 GEMM on the weights it multiplies.
Against the fp32 island the forward differs by 1.5e-3: bitsandbytes' fp32 forward dequantises straight to
fp32, while dequantize_4bit rounds to the quant state's bf16. The test now bounds that end-to-end gap by the
weight rounding instead of asserting 3e-5.
… straight to fp16

dequantize_4bit returns the quant state's dtype, bf16 on Z-Image, so the scaled GEMM multiplied weights with
8 mantissa bits; the fp32 island it replaces dequantises straight to fp32. Asking bitsandbytes for fp16 rounds
the exact nf4 value once. On a T4, against the fp32 island: forward 1.5e-3 -> 2.0e-4, input grad vs the exact
weights 1.6e-3 -> 2.9e-4. LoRA grads vs an all-fp32 reference (step 1): 1.49% -> 1.29% aggregate, median per
parameter 0.26% -> 0.12% (main 0.99%, 0.11%). Same speed (3.83 s/step), 68 scaled layers.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 8fe8abdf84

ℹ️ 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 +254 to +255
sub.__dict__["_unsloth_scaled_mm_orig"] = sub.forward
sub.forward = types.MethodType(_scaled_mm_forward, sub)

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 fp32 island when patching a bare nf4 linear

When custom LoRA targets omit to_out.0 or w2 (for example, a Q/K/V-only adapter), the island root is the bare bitsandbytes linear rather than a PEFT wrapper. make_fp32_island() first installs its fp32-casting forward, but this assignment immediately replaces it because module.modules() includes the root itself. Consequently, an fp16 input is no longer promoted, and _scaled_mm_forward() casts the fp32 GEMM result back to fp16 via y.to(x.dtype). Outputs above 65504 therefore overflow again in precisely the modules these islands protect, potentially making training repeatedly skip updates. Preserve the island wrapper around the scaled forward for bare-linear roots as well as PEFT-wrapped roots.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in a44ec33: install_fp32_islands now installs the scaled GEMM before the island, so on a bare nf4 root the island wraps the scaled forward (fp32 input, fp32 output). New test test_scaled_mm_on_a_bare_nf4_root_keeps_the_fp32_island feeds a finite fp16 input whose outputs reach 9.6e5: inf in fp16 before the change, finite fp32 matching the reference after.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: a44ec33a76

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 6b549ae9e4

ℹ️ 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 89a374f into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the studio-zimage-t4-fp16-islands branch November 23, 2026 22:08
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