Skip to content

Studio: run Z-Image and Wan2.2-5B / HunyuanVideo-1.5 in fp16 on fp16-only GPUs instead of fp32 - #12476

Merged
danielhanchen merged 12 commits into
mainfrom
studio/t4-fp16-dit
Oct 2, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
studio/t4-fp16-dit

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

On GPUs without bf16 (T4 and other sm75 cards), Studio promotes Z-Image and every video family from fp16 to fp32:

  • Z-Image is marked fp16_incompatible, and every VideoFamily defaults to fp16_incompatible = True.
  • fp32 doubles the weight bytes. Z-Image becomes about 39 GB dense and the Wan2.2-TI2V-5B transformer 31 GB, so the planner falls back to group offload and streams fp32 weights over PCIe on every step.
  • On a Kaggle T4, a Z-Image-Turbo 1024x1024 render takes 759 s (82 s/step). Wan2.2-TI2V-5B (25 frames, 20 steps) ran for 55 minutes and then ran out of host RAM at VAE decode. ComfyUI on the same VM runs both in fp16: Z-Image in 36.0 s and Wan in 214 s.

The promotion exists for a reason. Plain fp16 Z-Image overflows and renders black: LPIPS 0.87 to 0.95 against fp32. The fix has to keep fp16 accurate, not just switch it on.

Change

New diffusion_fp16_guard.py. Each family declares how it runs in fp16 (fp16_guard), and the old promotion stays the fallback:

family recipe why
Z-Image rescale_post_norm its attention and FFN branches overflow fp16
Wan2.2-TI2V-5B, HunyuanVideo-1.5 native fp16 output already matches fp32 (see Accuracy)
Wan2.2-T2V-A14B and every other family none (fp32 promotion as before) not measured as safe, or no gain
  • rescale_post_norm (Z-Image):
    • Measured in fp32 at 1024 px, the overflow is inside the attention and FFN branches. The FFN gate product reaches 2.9e5 and the attention output 1.4e5, against the fp16 max of 65504. The residual stream stays under 7.3e3.
    • Each branch output feeds an RMSNorm before the gated residual add, and rms_norm(y / s, eps / s^2) == rms_norm(y, eps). So the guard divides the branch by a power of two before the overflow point and divides that norm's eps by s^2. The result is the same function, with no clamping of real values:
      • attention: the block input is scaled by a pre-hook, the q / k RMSNorm eps is scaled with it, and v and the bias-free output projection are linear, so the output arrives already divided;
      • FFN: the w3 half of the gate is scaled before the product (silu applies to w1 only), so the product and w2 stay in range.
    • The hooks sit on the parent modules and call through to_q / w1 / ... at run time, so a LoRA wrapper or quantized Linear installed later sees the same reparameterisation. A block with a bias on those projections is not guarded.
    • A final nan_to_num to the fp16 range is a backstop only.
    • The guard checks the installed diffusers block source for the structure it depends on. If a diffusers release changes the block, the family falls back to fp32 promotion instead of running an unchecked fp16 path.
  • Where it applies: only where Studio would otherwise have promoted fp16 to fp32, meaning a load whose device resolves fp16 (GPUs without bf16). bf16 and fp32 loads are untouched.
  • Wiring: the dtype resolver in diffusion.py, the load paths in diffusion.py and video.py, and the video memory planner. The planner now sizes the guarded families at fp16, so on a T4 they can stay resident instead of being planned at fp32 size.
  • Kill switch: UNSLOTH_STUDIO_FP16_GUARD=0 restores the fp32 promotion for every family.

Results

Kaggle T4 (2x T4, 31 GB host RAM; Studio uses one card), Studio defaults, seconds per render:

family main (fp32 promotion) this PR ComfyUI, same VM type
Z-Image-Turbo 1024x1024, 9 steps 759.0 (81.9 s/step) 37.4 cold, 36.4 to 36.9 warm (3.8 s/step) 36.0
Wan2.2-TI2V-5B 1280x704, 25 frames, 20 steps host OOM at VAE decode after 55.8 min 302.1 cold, 279.4 new prompt (11.7 s/step) 213.9
  • Z-Image peak VRAM 11.5 GiB on the 15 GiB card. Both arms ran on the same VM, with the kill switch giving the main arm.
  • Wan now finishes on a 31 GB host. It is still 1.3x slower than ComfyUI per render, a gap that is not addressed here.

Accuracy

LPIPS against an fp32 reference with the same seeds and the same initial noise (generated on CPU):

arm prompts LPIPS mean / max PSNR
Z-Image, this PR, on a real T4 8 0.0048 / 0.0128 42.0 dB
Z-Image, this PR, on B200 8 0.0037 / 0.0084 42.4 dB
Z-Image, bf16 on B200 (for scale) 8 0.031 / 0.073 29.9 dB
Z-Image, plain fp16 (no guard) 2 0.87 / 0.89 (black) 7.9 dB
Wan2.2-TI2V-5B fp16, on a real T4, 9 frames 1 clip 0.0016 / 0.0018 51.2 dB
Wan2.2-TI2V-5B fp16, on B200 1 clip 0.0011 49.7 dB
HunyuanVideo-1.5 fp16, B200, 480p / 720p 1 clip each 0.044 / 0.036 30.3 / 32.3 dB
HunyuanVideo-1.5 bf16, B200, 480p (for scale) 1 clip 0.20 20.5 dB
  • On these families fp16 with the guard is closer to fp32 than bf16 is, which is what Studio already runs on bf16 GPUs.
  • The T4 and B200 Z-Image renders from this PR agree with each other at LPIPS 0.0046.
  • Wan2.2-T2V-A14B stays promoted. fp16 measured 0.158 against fp32 there, bf16 0.183, and the 14B experts do not fit a 16 GB card in fp16 either way, so it gains nothing.

Tests

  • New test_diffusion_fp16_guard.py covers:
    • family declarations: Z-Image stays fp16, an unguarded fp16-incompatible family still promotes, video families declare only native;
    • the kill switch, and a changed diffusers block keeping the promotion;
    • bf16 and fp32 never changing;
    • a synthetic overflowing block staying finite and matching fp32;
    • the guard against a real diffusers Z-Image block and its source;
    • install being idempotent and removable;
    • a biased block not being guarded;
    • a LoRA injected after install.
  • On main it errors at import.
  • test_diffusion_backend.py and test_video_backend.py are updated for the new resolver and planner sizes. Four of those tests fail on main as expected: Z-Image and Wan2.2-5B are no longer promoted, and the 5B is planned at fp16 size.
  • Together with test_diffusion_memory.py: 1202 passed, 1 skipped.

Not covered

  • HunyuanVideo-1.5 was measured on B200 only. On a Kaggle T4 the Studio download exceeds the disk cap, before and after this PR.
  • No other fp16-only card (RTX 20xx, V100) was run; they take the same path as T4.
  • Only NVIDIA was measured. A device without bf16 on another backend takes the same path as a T4 (fp16 with the guard instead of fp32) and was not run.
  • One clip per video family for accuracy, and one VM per T4 timing row.

…of promoting to fp32

Z-Image overflows float16 only in the attention and FFN branches that feed
the post-norm RMSNorm (FFN output up to 1.1e6 at 1024 px). Rescale those
branches by a power of two and divide the norm eps by its square, which is
the same function, so the model stays in float16 on T4 instead of being
promoted to float32 and streamed from host RAM.

Wan2.2-TI2V-5B is finite in plain float16 (DiT activations peak below 800),
so it opts out of the blanket video promotion.

The promotion is now decided per family by fp16_guard; families without a
recipe keep it. UNSLOTH_STUDIO_FP16_GUARD=0 restores the float32 promotion.
bf16 and fp32 loads are unchanged.
Both the 480p and 720p checkpoints stay finite in plain float16 (DiT peak
about 3e2, Qwen2.5-VL 7.4e3, VAE 2.2e2) and land closer to the float32
render than bf16 does, so they opt out of the float32 promotion like
Wan2.2-TI2V-5B. Wan2.2-T2V-A14B stays promoted: its float16 render drifts
from float32 about as far as bf16 does.

Log the kept float16 on the video path, keep the Wan VAE promotion test on
the kill switch, and add LoRA and plan-size coverage.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
🔒 Security Review 🔄 Running since 2026-10-01T23:21:15.626381Z 65fac0a 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 commented Oct 1, 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-10-02T08:50:49.880729Z 1b393ca Manual request
🔒 Security Review ⚠️ Failed 2026-10-01T23:21:18.730865Z 65fac0a 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

(Python 3.13, a-k) on head f31146db fails in the new test_guard_holds_through_a_lora_injected_after_install:

peft/tuners/lora/torchao.py:151: in dispatch_torchao
    from torchao.quantization import LinearActivationQuantizedTensor
ImportError: cannot import name 'LinearActivationQuantizedTensor' from 'torchao.quantization'

This is not this PR's bug. peft 0.18.1 runs dispatch_torchao for every LoRA target and torchao 0.18.0 removed that class; unsloth's #11168 fix only applies after import unsloth, which the diffusion process never does. So any Studio diffusion LoRA load on torch 2.12+ hits it, and this test is just the first to exercise it. #12494 adds the Studio-side guard; once it lands, a fresh push of this branch should clear the check.

…jection

peft's LoRA dispatch imports torchao symbols that the CI torchao no longer exports, so the test failed on
an unrelated dependency. A hand-written base + B @ A wrapper exercises the same property: Linear children
replaced after the guard is installed.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: 43d18ab1ce

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

import inspect
import sys

cls = getattr(importlib.import_module("diffusers"), cls_name)

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 Close the Dynamo import window before probing Diffusers

When the first Z-Image load runs before background warmup has completed or with warmup disabled, _target_for_ordinal() reaches this import from diffusion.py:5114, before close_dynamo_import_window() at line 5131. Importing Diffusers here therefore bypasses the synchronization that the load path explicitly requires before any Diffusers import and can reintroduce the concurrent torch._dynamo import race that leaves the process partially initialized; move this probe after that guard or make dtype resolution avoid importing Diffusers.

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 24742f5: the probe now calls close_dynamo_import_window before importing diffusers, and dtype resolution checks for float16 first so bf16 / fp32 loads never probe.

Comment on lines +213 to +215
logger.warning(
"diffusion.fp16_guard: recipe=%s matched no block; float16 output may overflow "
"(set %s=0 to promote to float32)",

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 Reject fp16 when no transformer block accepts the guard

If an allowed Diffusers release retains the source tokens checked by _recipe_supported() but changes the actual block topology—for example by adding a projection bias or moving one of the modules—dtype resolution has already selected fp16, while _block_sites() can reject every block here. Merely warning then runs Z-Image entirely unguarded in fp16, the exact path known to overflow and produce black images; the structural preflight must enforce the same conditions as installation, or a zero-site result must abort rather than continue.

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.

Not reachable: the Z-Image block (bias-free to_q/k/v/out and w1/w2/w3, diffusers RMSNorm with float eps, same norm/ffn names) is identical in every diffusers release that ships it (0.36.0 through 0.40.0) and the pinned main commit, and a real Studio load on 0.40.0 guards all 34 blocks. A zero-site install also logs a warning naming the kill switch.

…users

The recipe probe imports diffusers from dtype resolution, which runs before load_pipeline's own
close_dynamo_import_window call. Close the window in the probe itself, as the other early diffusers
probes do, and resolve the dtype first so bf16 and fp32 loads never probe at all.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: 24742f5017

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

inpaint_pipeline_class = "ZImageInpaintPipeline",
fp16_incompatible = True,
# The attention / FFN branches overflow float16 before their post-norm.
fp16_guard = "rescale_post_norm",

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 Honor fp16 guards in compile eligibility

On an fp16-only CUDA target with the Default or Max speed tier selected, this family retains fp16_incompatible=True, so diffusion_speed.compile_eligible() returns False at lines 338–339 even though this recipe now keeps the effective target in float16. Regional compilation is therefore silently disabled for Z-Image, as it is for the newly native video families, leaving requested speed optimizations—and potentially torchao transformers that rely on compilation—on the eager path. The compile gate should test whether the family actually promotes to fp32 rather than the legacy incompatibility flag alone.

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.

Intentional: compile_eligible keeping guarded fp16 families eager is what keeps them correct. The compile path installs the int8 fused MLP, which replaces the FeedForward instance forward the guard relies on (diffusion_int8_fused.install sets module.forward), so compiling would bring the fp16 overflow back. Speed is not the goal on these cards; the measured T4 numbers in the description are eager. Noted the reason at the gate in 1b393ca.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 1b393ca7ae

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

# Conflicts:
#	studio/backend/core/inference/diffusion.py
# Conflicts:
#	studio/backend/tests/test_diffusion_backend.py
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