Repository navigation
Studio Z-Image fp16 training: scaled fp16 GEMMs instead of fp32 islands on T4 (1.7x per step) - #19057
Conversation
…th fp32 output instead of fp32 sgemm islands
…i + lo parts in the forward
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
|
@codex review |
There was a problem hiding this comment.
💡 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".
| sub.__dict__["_unsloth_scaled_mm_orig"] = sub.forward | ||
| sub.forward = types.MethodType(_scaled_mm_forward, sub) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…GEMM on a bare nf4 linear [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…thout tensor cores) [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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.0andfeed_forward.w2run 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:
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:
to_out.0w2layers.0), output: 14 of 34w1(fp16, reference)w2's input is fp32 (the LoRA wrapper returns fp32 forw1/w3), sosilu(w1) * w3reaches 2.3e5 before the island.How
diffusion_dit_fp16.py:FP16_SCALED_MM_MODULES(Z-Imageto_out.0andw2only). The island still turns autocast off and runs the LoRA branch in fp32. Only the nf4 base matmul changes.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.torch.mmhas noout_dtype, on GPUs below sm70, for a weight past the fp16 range, or withUNSLOTH_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_completedreportsfp16_scaled_mm(layers installed, 68 on Z-Image). At the end of the run,fast_lora_stats(orfp16_statswithout fast LoRA) addsfp16_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_4bitreturns 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: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:
w2forward errorw2forward timew2input-grad errorw2input-grad timeto_outforward timeEvery other nf4 linear in the step already runs fp16 in and out:
w1measures 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:
noise_refiner.0.feed_forward.w3.lora_B)layers.15.attention.to_k.lora_B)noise_refiner.0.feed_forward.w3.lora_B)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:
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:
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 isyuvalkirstain/PickScore_v1. Both score against the prompt without the trigger words: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:
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).
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:
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.pyon 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):to_out.0/w2only, and the kill switch installs nothingtorch.mmwithoutout_dtypew2(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
mm(out_dtype=)take the fp32 fallback, which has only CPU tests. The per-device probe has only CPU tests with mocked devices.