Skip to content

Studio: re-decode a NaN 16-bit VAE decode in fp32; fp32 VAE on GPUs without tensor cores (GTX 16xx) - #18454

Merged
danielhanchen merged 3 commits into
mainfrom
studio-vae-fp32-nan-retry
Nov 20, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
studio-vae-fp32-nan-retry

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

A GTX 1650 user on Windows gets HTTP 500 "The decoded image contains NaN values" at the end of every render, with FLUX.2 klein 4B GGUF and Z-Image Turbo, even at 256x256. The same setup works on an Intel iGPU.

On an NVIDIA card these picks run through diffusers. Below compute capability 8.0 there is no bf16, so the whole pipeline runs in float16, including the VAE. GTX 16xx cards (TU116/TU117, no tensor cores) are widely reported to produce NaN or black images from float16 convolutions; other Stable Diffusion front ends special-case this card family. They report the same compute capability (7.5) as the T4 and RTX 20xx, so nothing in Studio told them apart.

On main, the only NaN-to-fp32 VAE fallback covers the SDXL VAE (plus a separate one for video VAEs). For the other image families the NaN surfaces only in postprocess, after the latents are gone, so a VAE overflow and a denoiser overflow look the same.

Change

New module diffusion_vae_finite.py, plus a 7-line hook in diffusion.py next to the existing SDXL fp16 decode setup.

  • Safety net, every card: a 16-bit decode that returns NaN/Inf from finite latents is decoded again once in fp32 from the same latents, and that VAE then stays fp32. If the latents themselves are non-finite, a new message names the denoiser instead. Weights stay stored in 16 bits and are upcast per call, so offload and memory placement do not change. A clean decode costs one finiteness check, right before the existing postprocess check.
  • Cards without tensor cores: the VAE decodes and encodes in fp32 from the start. That covers capability 7.5 with a GTX 16xx, MX450/MX550 or Quadro T400 to T2000 name, and anything below capability 7.0. Tesla T4, RTX 20xx, Quadro RTX and TITAN RTX are excluded. The SDXL fp16 decode also stays off on these cards. The denoiser dtype is unchanged.
  • Switch: UNSLOTH_DIFFUSION_VAE_FP32. 1 forces fp32, auto is the default, and 0 turns the whole layer off (main's behaviour).

Results

Colab T4, FLUX.2 klein base and Z-Image Turbo at 256 and 1024 px, merge base vs this branch:

  • No NaN: byte-identical images at both sizes for both models, with 0 retries and 0 fp32 decodes on this branch. The klein comparison uses arms with the same offload layout; klein's first load after download picks a different layout, which differs slightly on its own (LPIPS 0.00056 at 1024).
  • NaN injected into the VAE decoder output:
    • Main raises the user's exact error at both sizes, for both models.
    • This branch returns the image: 1 retry, an fp16 then an fp32 decode, and later decodes stay fp32.
  • The retry is exact: its output is byte-identical to an fp32 decode from the start, for both models.
  • Quality: fp32 vs fp16 decode LPIPS is 1e-5 to 6e-5, below the 5.6e-4 run-to-run floor.
  • Latents: they entered the VAE finite at both sizes for both models.

Tests

  • tests/test_diffusion_vae_finite.py, 43 CPU tests:
    • the card table (22 names);
    • a clean decode equal to stock for both VAE classes;
    • a NaN decode re-decoding in fp32, equal to an fp32 decode, with weights left fp16;
    • NaN latents raising the denoiser message;
    • the forced and per-card modes, the env switch, and compile-slot compatibility.
  • Neighbouring VAE, speed and OOM suites pass.

Not covered

  • The GTX 16xx trigger itself: no TU116/TU117 card exists on Colab, Kaggle or our CI, and the T4 does not produce the NaN. That the fp32 VAE cures it on that card is inferred from the user's report (normal preview, failure at decode) and from other front ends' handling of this family.
  • Windows, the torch 2.6 / transformers 4.57.6 floor, and whether an fp32 decode at 1024 fits in 4 GB. If it does not, the existing OOM handling (offload, then tiling) wraps this layer.

… GPUs without tensor cores

A NaN or Inf decode from finite latents is decoded again once in fp32 from
the same latents, and later decodes of that VAE stay fp32. Non-finite
latents raise a message that names the denoiser. GTX 16xx, MX450/MX550,
TU117 Quadro/T-series and pre-Volta cards decode and encode in fp32 from
the start, and keep the SDXL fp32 upcast. Weights stay stored in 16 bits.
UNSLOTH_DIFFUSION_VAE_FP32=1 forces fp32, 0 turns the layer off.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 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-19T11:50:47.838989Z ce96fa0 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 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: ddee701822

ℹ️ 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 +184 to +185
with fp32_keeping_storage(vae, encode_parts):
return encode(x.to(torch.float32), *args, **kwargs)

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 Preserve the encoder output dtype after fp32 computation

When fp32 mode is forced or automatically enabled on a GTX 16xx, this wrapper changes the encoded latent distribution from 16-bit to float32 without restoring the caller's expected dtype. This breaks dense 16-bit FLUX img2img: FluxImg2ImgPipeline.prepare_latents passes the encoded latents through scheduler.scale_noise without casting them back, and its denoising loop sends those float32 latents directly into the transformer's 16-bit x_embedder, causing a matrix dtype mismatch. Keep the encoder arithmetic in fp32, but restore the latent distribution's output dtype (or explicitly adapt the affected pipeline consumers) before returning.

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 ce96fa0. The encoder still runs in fp32, and the output (tuple, AutoencoderKLOutput and the DiagonalGaussianDistribution's parameters, mean, std, var) is handed back in the VAE's 16-bit dtype, so img2img latents reach the denoiser in its dtype. test_fp32_from_the_start now asserts the 16-bit dtypes and a 16-bit sample; it fails on the previous head.

@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. 🎉

Reviewed commit: ce96fa0d75

ℹ️ 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 07d7976 into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the studio-vae-fp32-nan-retry branch November 20, 2026 02:45
danielhanchen added a commit that referenced this pull request Nov 20, 2026
…decode test (#18561)

## Summary

`Repo tests (CPU, rest-2)` is red on `main` (and so on every PR) because
`tests/test_source_read_encoding.py` flags a new read:

```
AssertionError: 1 file reads in the test trees touch a checked-in file with the platform default encoding, so they break on Windows as soon as that file gains a non-ASCII byte. Pass encoding = "utf-8": ['studio/backend/tests/test_diffusion_vae_finite.py:281: read_text()']
```

## Cause

#18454 added `test_load_installs_before_the_speed_layer`, which reads
`studio/backend/core/inference/diffusion.py` with a bare `read_text()`.
On Windows that uses the locale code page, so the test breaks as soon as
`diffusion.py` gains a non-ASCII character. The guard is right; the new
read is the problem.

## Change

- `studio/backend/tests/test_diffusion_vae_finite.py`: pass `encoding =
"utf-8"` to that one `read_text`. No behaviour change.

## Testing

- `tests/test_source_read_encoding.py`: fails on `main` with the
offender above, passes with this change (16 passed).
- `studio/backend/tests/test_diffusion_vae_finite.py`: 43 passed.
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