Skip to content

Studio: offload-first retry for an OOM VAE decode, fuse GroupNorm+SiLU on uncovered VAEs by structure - #13802

Merged
danielhanchen merged 39 commits into
mainfrom
studio-diffusion-vae-oom-retry-structural-fused
Oct 20, 2026
Merged

danielhanchen merged 39 commits into
mainfrom
studio-diffusion-vae-oom-retry-structural-fused

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Problem

  1. A VAE decode that runs out of memory fails the whole render after the denoiser has finished.

    • An untiled image decode has no retry.
    • Studio's wide-tile decoders fall back only as far as the stock tiles.
    • A stock tiled decode that still does not fit, image or video, raises.

    On a small card this throws away a finished denoise because of the last stage. Studio's planner already predicts the decode peak and turns tiling on before the render when the untiled decode would not fit (calibrated decode_mib / tiled_decode_mib, ACTIVATION_TILE -> engage_vae_tiling; video_vae_untiled for video), so this is only the runtime fallback for a misprediction: another process taking VRAM mid-render, fragmentation, an uncalibrated family.

  2. Fused VAE kernels only engage on a fixed list of classes. diffusion_vae_fused fuses GroupNorm+SiLU for AutoencoderKL, FLUX.2, Qwen-Image, Wan and LTX-2. Any other diffusers VAE, such as HunyuanImage-2.1's AutoencoderKLHunyuanImage, decodes fully unfused.

Change

1. Offload-first retry on a decode OOM (new diffusion_vae_oom.py, wired in diffusion.py and video.py)

The retry wraps _decode on every diffusers VAE. Each step runs only if the previous one still runs out of memory:

  • (a) Free the card, same decode. Everything else on the decode's device that the decode does not need leaves it, through Studio's existing paths:

    • captured CUDA graphs are dropped (diffusion_cuda_graph.reset_all, as both backends already do on any OOM; they re-capture on the next step);
    • resident offload groups stream again, text encoders first, then the denoiser's blocks (release_resident_groups, the path an oversized request uses);
    • pipeline components that sit whole on the card without offload hooks (transformer, text encoders, audio VAE, ...) move to the host, largest first, while host RAM allows.

    The same decode is then retried: an untiled decode stays untiled.

  • (b) Stock tiles. An untiled decode retries tiled at the VAE's own tile sizes. This is ComfyUI's single tiled retry.

  • (c) Stream the VAE. The VAE's weights stream from the host per layer (diffusers leaf-level group offload) for one more decode at stock tiles.

Rules:

  • Tile sizes are never changed. Tiles under the stock size bring back visible seams (Qwen-Image-2.1's vertical lines came from 16-latent tiles), so there is no smaller-tile step.
  • Everything moved comes back, transactionally. Each change (graphs dropped, groups released, component moved, VAE hooks added) is an undo entry that leaves the log only once its own undo succeeded. If the card filled up meanwhile, the undo leaves the module whole on the host with a working path: the VAE keeps its offload hooks and returns at its next decode; a component gets a deferred return (forward pre-hook, plus an accelerate-shaped _hf_hook whose execution_device keeps DiffusionPipeline._execution_device on the card) that is removed only after the move succeeds. A deferred return is required unless the module is checked to run where it is (the VAE streaming whole from the host under its hooks, offload groups keeping theirs); a decode whose required VAE repair still fails raises that error instead of decoding on a split VAE.
  • uninstall removes the _decode wrapper and the compiled-decode guard and settles every deferred return the wrapper registered (one that still cannot run stays: it is that module's only way back).
  • Under torch.compile: the _decode wrapper is a pass-through. A compiled decode that runs out of memory frees the card and retries the compiled decode first (same kernels), then falls to the eager path, where the ladder continues with the same session. The scope is always the outermost decode layer, above the fp16 / ROCm bf16 dtype wrappers, the untiled-when-fits gate and any compiled guard, so an OOM in a wrapper's own allocation reaches it too, and it climbs the same rungs as the _decode ladder (free the card, stock tiles, VAE streamed) through the same session; a compiled guard anywhere below runs its eager path while the scope asks for it. Anything that rewraps vae.decode after load (a deferred speed profile, a VAE compile, a compile fallback, the H3 speedups) re-asserts it, and it re-asserts itself when a decode closes. Every retry after a decode that failed part way (wide tiles, LTX-2 tiles, untiled gate, the ladder's own steps) clears a causal decoder's cache first.
  • Decodes that fit take one try and nothing else.
  • ComfyUI's behaviour, for reference: VAE.decode (comfy/sd.py) calls load_models_gpu([vae], memory_required=estimate) before decoding, and free_memory (comfy/model_management.py) unloads the diffusion model and text encoders from the card until the estimate fits; on an OOM it retries once with decode_tiled_ at its normal tiles (64-latent tiles, 16 overlap) and never goes smaller. A VAE that still does not fit runs in lowvram mode with its weights partly on the host. Unloaded models reload at the next load_models_gpu.
  • Off switch: UNSLOTH_VAE_OOM_RETRY=0. Counters and timings are on vae._unsloth_vae_oom_stats.

2. Fused GroupNorm+SiLU matched by structure (diffusion_vae_fused.py, unchanged)

For a VAE class outside the measured list whose decoder uses plain nn.GroupNorm:

  • Detection: the first CUDA decode traces a small crop of the real latent with forward hooks to find each GroupNorm whose every output feeds an nn.SiLU.
  • Fusion: those norms get the fused GroupNorm+SiLU kernel; the other norms get the fused GroupNorm.
  • Validation: the fused crop must match stock (max abs 0.125, mean 0.01), otherwise the patch is removed.
  • Exclusions: classes already on the list keep their existing path and stay bit-identical. A family that owns its decoder fast path is skipped.
  • Off switch: UNSLOTH_VAE_FUSED_STRUCTURAL=0.

Results

Decode speed (structural fusion), B200, bf16, median of 5 decodes from a real encoded latent:

VAE class main (A/A) this PR off switch peak MiB main -> PR output vs main
AutoencoderKLHunyuanImage (HunyuanImage-2.1), 2048 px 0.284 / 0.284 s 0.099 s (2.9x) 0.285 s 5120 -> 3584 LPIPS 0.00011
AutoencoderKL (FLUX.1), 1024 px 0.0190 / 0.0185 s 0.0188 s 0.0202 s 1408 -> 1408 bit-identical
AutoencoderKLFlux2, 1024 px 0.0200 / 0.0200 s 0.0200 s 0.0185 s unchanged bit-identical
AutoencoderKLQwenImage, 1024 px 0.0106 / 0.0109 s 0.0114 s 0.0115 s unchanged bit-identical
AutoencoderKLWan (Wan2.2-5B), 33 frames 480x832 0.535 / 0.531 s 0.540 s 0.530 s unchanged bit-identical
AutoencoderKLLTX2Video (LTX-2.5), 33 frames 512x768 0.0386 / 0.0390 s 0.0389 s 0.0389 s unchanged bit-identical
  • On HunyuanImage-2.1 the structural path fused 41 GroupNorm+SiLU and 1 GroupNorm, with 294 fused calls over the timed decodes. With the off switch the output is bit-identical to main.
  • First decode, once per process (B200 exclusive, HunyuanImage-2.1 2048 px, 3 fresh processes, median [range]): the earlier revision of this PR (7fe6a3a) 0.61 s [0.59-0.64], this PR 0.72 s [0.69-0.82] on the first run and 0.62 s [0.49-0.67] once the structural verdict is cached. With a cold Triton cache: earlier revision 4.61 s [4.36-4.99], this PR 4.72 s [4.50-5.03], cached 4.37 s [4.03-4.40]. Steady decodes are 0.095 s on both.
  • The structural verdict (which GroupNorm feeds which SiLU, and whether the crop check passed) is cached under the Studio compile cache root, keyed by VAE class, decoder config, torch, Triton and GPU capability. UNSLOTH_VAE_FUSED_STRUCTURAL_CACHE=0 turns the cache off.
  • A fused GroupNorm+SiLU output gives the activated values only to the SiLU it was traced into, once. Any other read (a residual, another norm, a view or in-place write, a raw pointer, a later or reused SiLU) stops that decode, which is then redone with GroupNorm fused alone for this VAE (the cached verdict is downgraded too). So the result never depends on the calibration crop having the same dataflow as the full-size decode, and nothing keeps the norm's input around for a later recompute.
  • The verdict cache key also covers the decoder weights (names, shapes, dtypes and leading values of every tensor) and hook state, so one checkpoint's verdict never authorises another.

OOM ladder, Colab A100 40 GB, bf16, real encoded latents. Each VAE sits beside a resident 4.5 GiB "transformer" and 1.5 GiB "text encoder", as in a resident Studio pipeline at decode time. A per-process cap is lowered until each step is the one that recovers. Main (merge base) fails every row below.

VAE / case step that recovers cap (MiB) main decode time, uncapped -> recovered of which free + restore output vs the same decode by hand at the same free memory vs uncapped decode seam score (uncapped)
AutoencoderKL (FLUX.1), 2048 px untiled (a) freed, untiled 12979 OOM 0.80 -> 8.6 s 4.7 + 3.2 s bit-identical 70.7 dB, LPIPS 0.00001 1.134 (1.133)
AutoencoderKL (FLUX.1), 2048 px untiled (b) stock tiles 3123 OOM 0.80 -> 6.7 s 4.2 + 0.4 s 75.6 dB 74.0 dB vs uncapped tiled, LPIPS 0.00001 1.123 (1.133)
AutoencoderKL (FLUX.1), 2048 px untiled (c) VAE streamed, stock tiles 2472 OOM 0.80 -> 8.8 s 4.2 + 0.5 s bit-identical 72.4 dB vs uncapped tiled, LPIPS 0.00001 1.123 (1.133)
AutoencoderKL (FLUX.1), 2048 px tiled (a) freed, tiled 7367 OOM 1.56 -> 7.0 s 4.2 + 0.4 s bit-identical 69.2 dB, LPIPS 0.00001 1.122 (1.123)
AutoencoderKLWan (Wan2.2-5B), 704x1280, 41 frames, tiled (a) freed, tiled 8031 OOM 9.8 -> 18.3 s 4.2 + 0.4 s bit-identical 66.9 dB, LPIPS 0.00001 1.072 (1.071)
AutoencoderKLWan (Wan2.2-5B), 704x1280, 41 frames, tiled (c) VAE streamed, stock tiles 2576 OOM 9.8 -> 349.5 s 4.2 + 0.4 s bit-identical 64.3 dB, LPIPS 0.00002 1.072 (1.071)
AutoencoderKLLTX2Video (LTX-2.5), 512x768, 33 frames, tiled (B200) (a) freed, tiled 7645 OOM not timed not timed bit-identical 61.1 dB, LPIPS 0.00004 1.059 (1.059)
AutoencoderKLLTX2Video (LTX-2.5), 512x768, 33 frames, tiled (B200) (c) VAE streamed, stock tiles 1608 OOM not timed not timed bit-identical 58.6 dB, LPIPS 0.00007 1.059 (1.059)

The LTX-2.5 rows ran on a shared B200 (the Colab job could not fetch the gated weights; the retry could not get a VM), so they are an accuracy check only, with no timing.

  • Step (a) changes nothing in the math. Its output is bit-identical to a stock decode run by hand with the same memory free. Against an uncapped decode it is 61 to 71 dB (LPIPS at most 0.00004): with less free memory cuDNN picks a different convolution algorithm, which main does too under the same pressure.
  • No seams at any step. The seam score (mean abs pixel difference across each tile boundary row / col over the median of all rows / cols; 1.0 is clean, visible seams measured 11 to 32 on Qwen-Image-2.1 16-latent tiles) stays at the untiled reference's level.
  • Time: the recovered decode costs moving the 6 GiB of other components to the host and back (about 4 s out, 0.4 to 3 s back on this VM) plus the decode at the lower free memory. Streaming the VAE (c) is slow for a causal video VAE: Wan2.2-5B took 350 s, and the same streamed decode done by hand took 322 s, so the cost is the streaming itself. It is the last step before failing.
  • Restore: after every recovery the components were back on the card, the VAE had no offload hooks left and its tile sizes were the stock ones. Under caps below the pipeline's own resident size, the transformer could not return inside the cap and came back on its next forward, as designed.
  • Decodes that fit: bit-identical to main, same time (FLUX.1 untiled 0.802 / 0.803 s, FLUX.1 tiled 1.564 / 1.559 s, Wan2.2-5B 9.799 / 9.816 s, main / this PR; LTX-2.5 bit-identical, not timed).

Tests

  • tests/test_diffusion_vae_oom.py covers:
    • each ladder step on a fake card, with the step before it failing first: (a) retries the same untiled decode, (b) stock tiles, (c) the streamed VAE;
    • tiles never leave the stock sizes;
    • components, resident groups and CUDA graphs: dropped for the retry, back afterwards; a component that cannot return comes back on its next forward;
    • offload-hooked components left to their mechanism, host RAM limits respected;
    • a broken streamed decode fails on the original out-of-memory;
    • the compiled-decode guard: compiled retry after freeing, then the eager ladder with the same session;
    • the untiled-when-fits gate keeps its own fallback, the off switch, uninstall / reinstall;
    • a real tiny diffusers VAE round trip through leaf-level offload hooks (bit-identical, hooks gone);
    • structural matching and its exclusions.
  • New tests/test_diffusion_vae_oom_faults.py: fault injection over a fake pipeline (resident transformer, three resident offload groups, CUDA graphs, a VAE with an instance-bound _decode override under a later decode wrapper, a 3-sample sliced decode). Across 5 memory caps x untiled / tiled callers it injects an out-of-memory or a generic error at every mutation point of the ladder and of the restore (386 cases), then checks that every module is back on its card or has a working deferred return, resident groups are all re-pinned or consistently streamed, later slices never take a cheaper path than an earlier one, the decode's own OOM surfaces when nothing recovers, and uninstall leaves the wrapper stack exactly as before.
  • CPU: the VAE files, the fault-injection file and every test file that touches release_resident_groups (29 files): 4123 passed, 179 skipped. test_diffusion_vae_oom.py alone: 46 passed, 2 CUDA-only skips.

Not covered

  • Real renders: the OOM evidence comes from per-process caps on a pipeline stand-in (random-weight resident modules), not from full Studio renders at a card's real limit with another process taking memory.
  • Studio's real placements: torchao-quantised components are left in place by (a) (their own release path, hook_resident_denoiser, is not called); offload-hooked components are left to their mechanism. How much (a) frees in each Studio memory mode was not measured.
  • Deferred return in a real render: a component left on the host carries an _hf_hook whose execution_device is the card, so _execution_device resolves the card (tested on a tiny diffusers pipeline); not exercised in a full Studio render at a real limit.
  • Unified memory (GB10, Strix Halo, Apple): moving to the host frees nothing there; the ladder then costs the copies and goes on to (b) and (c).
  • Step (c) on causal video VAEs works but is about 35x slower (Wan2.2-5B); block-level streaming was not tried.
  • FLUX.1 tiled step (c) was not hit by the cap search (step (c) is shown on the same VAE for the untiled caller).
  • Untested environments:
    • Windows WDDM spills to host memory instead of raising OOM, so the retry does not fire there.
    • HIP and Metal: the structural path is NVIDIA + Triton only; the ladder ran on CUDA only.
    • torch 2.6 dynamo behaviour of the wrapper.
  • Untested VAEs: AutoencoderKLQwenImage21 and HunyuanVideo-1.5 with real weights.

Tests (addendum)

  • Merged current main (one conflict in release_resident_groups: main's tied-partner streaming kept, with this PR's rule that each group is recorded as streamed before it is demoted, so a release that fails part way is still re-pinned by restore).
  • test_vae_restore_oom_keeps_offload_hooks_and_retries and test_real_vae_offload_hooks_round_trip use CPU onload as a stand-in for the card. diffusers 0.36 (the Python < 3.10 pin) builds group offloading only when an accelerator is present, so on a CPU-only host these two now skip with a reason instead of erroring. On diffusers 0.41 they still run with no GPU visible.
  • Version corner, torch 2.6.0 (CPU) + diffusers 0.36.0 + transformers 4.57.6: test_diffusion_vae_oom.py + test_diffusion_vae_oom_faults.py 3462 passed, 2 skipped (CUDA-only), and the two above, which errored before and now skip.

… fused GroupNorm+SiLU for uncovered classes

diffusion_vae_oom wraps the instance _decode: an untiled decode that runs out of memory is retried tiled,
a tiled one with every spatial tile attribute halved (overlap fraction kept, so the stock blend still
crossfades seams) down to a 4-latent floor; the working level is memoised per latent shape. Wide-tile
overrides (image, LTX-2) defer to the stock tiled decode while a halving runs. UNSLOTH_VAE_OOM_RETRY=0.

diffusion_vae_fused: VAEs outside the measured class set whose decoder runs plain nn.GroupNorm get the
fused GroupNorm(+SiLU) kernel, paired by the dataflow of one tiny decode on the first CUDA call and kept
only when the fused tiny decode matches stock. UNSLOTH_VAE_FUSED_STRUCTURAL=0.
… tiles do not lower the peak, discard wrong-size outputs

HunyuanImage-2.1's 12-latent tiles halved to 6 step 4 latents but keep 144 px, so diffusers' stock tiled decode
returned 2288 px for a 2048 px image: halvings now keep every size a whole number of latents and tile_overlap_factor
steps whole. A causal video decoder whose peak is not in its tiles (Wan) stops after one halving fails to lower the
failing peak instead of walking to the floor, and a memoised level that fails falls back to the stock tiles.
…rame cache after a failed attempt

HunyuanImage-2.1 halved to 4-latent tiles decoded at LPIPS 0.46 against the untiled decode; the floor is now
8 latents (the last halving lands on it).
Under a hard cap (or a full card) every failed attempt peaks at the limit, so the stop fired after one halving
on FLUX.1 where three more halvings decode. The 8-latent floor already bounds the ladder to a few attempts.
… tiles when memory frees

Before a halved level is used it decodes a 3-tile corner crop against the untiled crop and must reach 30 dB
(FLUX.1 16-latent tiles 36.8 dB, LTX-2.5 8-latent 33.5, HunyuanImage-2.1 8-latent 26.7 at LPIPS 0.19); a
refused level fails the decode as before. A remembered level is dropped once 25% more memory is free than
when the stock tiles failed.
…atent tiles

Under a tight cap the untiled 3-tile crop itself ran out of memory and the probe let HunyuanImage-2.1's
8-latent tiles through. The crop now spans one seam each way, and a level the probe could not measure is
only used when its tiles are at least 16 latents.
@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
📝 Code Review 🔄 Running since 2026-10-15T05:18:34.994789Z 53cfb1a 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 15, 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 ⚠️ Failed 2026-10-20T20:39:23.345872Z
We couldn’t complete this review. Comment @codex review to try again.
427a9ba New commits
🔒 Security Review ⚠️ Failed 2026-10-15T05:18:39.737923Z
We couldn’t complete this review. Comment @codex security review to try again.
53cfb1a 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

@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: 91827b820d

ℹ️ 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 +1109 to +1110
inner = vae.__dict__.pop("_unsloth_vae_structural_inner", None)
if inner is not None and getattr(vae.__dict__.get("_decode"), "_unsloth_vae_fused", False):

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 Unwrap structural decode beneath the OOM retry

When structural fusion and the new OOM retry are both enabled, the normal loader installs the OOM wrapper after the speed layer, so the current _decode is marked _unsloth_vae_oom_retry rather than _unsloth_vae_fused. This condition therefore skips restoration while immediately discarding the saved inner function and state; calling diffusion_vae_fused.uninstall leaves the structural wrapper trapped beneath the OOM wrapper, and if calibration is still pending it can repatch the decoder on the next call. The uninstall path needs to preserve or explicitly traverse the wrapper chain.

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 a62f89d. uninstall now checks whether the OOM retry wraps the structural layer. If it does, it removes the retry, restores the original decode, then reinstalls the retry on top, so the calibrator can no longer stay or repatch underneath. Test: test_uninstall_unwraps_structural_layer_under_the_oom_wrapper.

Comment on lines +252 to +253
tiled = _decoded(_attempt(level, crop, args, kwargs)).float()
mse = float((tiled - ref).pow(2).mean())

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 Validate probe shapes before computing PSNR

When a halved stock tiled decode returns a different spatial shape for the probe crop, this subtraction either raises a tensor-size error or broadcasts incompatible outputs instead of treating that tile level as unusable. The full retry path explicitly anticipates such VAEs through _shape_ok, but the probe runs first, so an initial OOM can terminate with an unrelated shape exception before smaller tile levels are attempted. Compare the probe shapes before calculating MSE and reject or skip malformed levels.

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 a8a60f6. The probe compares the crop shapes before computing the MSE. A mismatch marks that tile level as unusable and the retry moves on to the next level, instead of raising or broadcasting. Test: test_probe_shape_mismatch_falls_through_to_the_next_level.

if level > start:
break
continue
if level and not _level_quality_ok(level, z, 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.

P1 Badge Clear failed decoder caches before running the next probe

After one tile attempt OOMs, the next loop iteration calls _level_quality_ok before _release_cache. This module explicitly accounts for causal decoders retaining failed-attempt tensors in clear_cache, so the probe can run with that stale cache and spuriously OOM; at an 8-latent level, such an unmeasurable probe is rejected because it is below UNPROBED_MIN_LATENTS, causing the render to fail even though the actual tile could fit after cache clearing. Release the failed attempt's cache before probing the next level.

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 a8a60f6. The failed attempt's cache is now released before the next level's quality probe, so a causal decoder's stale frame cache no longer makes the probe run out of memory. Test: test_cache_released_before_the_quality_probe.

Comment on lines +174 to +176
def _outer_gate_owns_untiled(vae: Any) -> bool:
"""video_vae_untiled's gate turns tiling off for its own attempt and retries tiled itself."""
return bool(getattr(vae.__dict__.get("decode"), "_unsloth_untiled_decode", False))

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 Follow wrapped decodes when detecting the untiled gate

On supported ROCm video loads, install_untiled_decode is followed by install_rocm_vae_bf16_decode, whose replacement exposes the gate only through __wrapped__ and does not copy _unsloth_untiled_decode. This direct marker check therefore misses the gate: when its estimated untiled decode OOMs, the inner OOM wrapper performs and may recover through its own tiled ladder, so the gate records the call as untiled and never memoizes oom_need; every subsequent render of that size retries the known-failing untiled decode. Walk the __wrapped__ chain or propagate the gate marker.

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 a8a60f6. The untiled gate check now follows the wrapped chain (bounded at 8 hops), so it finds the gate behind the ROCm bf16 decode wrapper. Test: test_untiled_gate_found_through_wrapped_chain.

…p a level whose probe crop is the wrong size, find the untiled gate through __wrapped__

The probe of the next level ran against the failed attempt's stale causal-decoder cache and could OOM,
refusing an 8-latent level that fits. A tiled probe crop of a different size than the untiled crop now marks
that level unusable and the ladder moves on instead of raising. The untiled-when-fits gate is found through
the ROCm bf16 decode's __wrapped__ chain (bounded).
…all, restore the conv layout on rejection

uninstall now removes the structural calibrator even when the OOM retry wraps it (the retry is lifted,
the inner restored, the retry reinstalled). The channels_last(_3d) decode weights relaid because fusion was
planned are recorded and put back to contiguous when structural calibration is rejected.
@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: a62f89d41a

ℹ️ 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 +110 to +111
if lat < MIN_TILE_LATENTS or lat >= prev or lat >= base_latent:
return None # under the floor, or no smaller than the previous level

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 Continue halving other axes after one reaches the floor

When a VAE exposes asymmetric height and width tile sizes, this returns None as soon as either axis was already clamped to MIN_TILE_LATENTS, even if another axis can still shrink. For example, 32×16-latent stock tiles reach 16×8 at level 1, but level 2 is rejected because the width remains 8, so the retry never attempts the potentially fitting 8×8 tiles and reports that every tile size OOMed. Treat an axis already at the floor as unchanged and return None only when no axis can be reduced.

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 656d184. halved now works per axis: an axis already at the 8-latent floor keeps its last size while the other axes keep halving, and it returns None only when no axis gets smaller at that level. 32x16-latent stock tiles now go 16x8, then 8x8. Test: test_halving_continues_on_the_axis_above_the_floor.

Comment on lines +269 to +271
_release_cache(z, vae)
stats["probe_psnr"][level] = None
return lat >= UNPROBED_MIN_LATENTS

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 Cache the fallback decision after a probe OOM

When the quality probe OOMs for a level of at least 16 latents, this permits the level but does not store the result in quality. If that level recovers the render and is memoized, every subsequent render of the same shape still reruns the known-failing probe before using the working tiles, causing an avoidable OOM and cache flush on every call. Cache the allowed unprobed result (or memoize the probe failure with an appropriate memory invalidation rule) so the working-level memo can actually bypass it.

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 656d184. When the probe runs out of memory and the level is still allowed (16 latents or more), that allowance is now cached, so a remembered working level goes straight to its tiles without rerunning the probe. A refusal under 16 latents is not cached, so the probe can run again once more memory is free. Test: test_unprobed_level_is_remembered_with_the_working_level.

Comment on lines +63 to +68
boc = cfg.get("block_out_channels") if hasattr(cfg, "get") else getattr(cfg, "block_out_channels", None)
if boc:
return 2 ** (len(boc) - 1)
except Exception: # noqa: BLE001
pass
return 8

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 Derive the ratio from the exposed tile geometry

For a tileable VAE that does not publish spatial_compression_ratio or block_out_channels but does expose both tile_sample_min_size and tile_latent_min_size, this silently assumes an 8× ratio instead of using their quotient. On a 16× or 32× VAE, retries then write incorrect sample-space tile sizes and _shape_ok compares the result against the wrong expected dimensions, so a valid smaller-tile decode is discarded and the render ultimately fails. Use the sample/latent tile ratio before falling back to 8, as the existing tiling geometry helper already does.

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 656d184. Before falling back to 8, _spatial_ratio now uses the quotient of the exposed tile_sample_min and tile_latent_min sizes on any axis. Test: test_ratio_from_tile_geometry_when_nothing_else_publishes_it.

… an unprobed working level, take the ratio from the tile geometry
@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: 656d184b42

ℹ️ 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 +255 to +256
if level in quality:
return quality[level]

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 Recheck seam quality for each latent

When one input passes the probe at a given halving level, this global quality[level] cache allows that level for every later image or video decoded by the VAE. PSNR depends on the latent content and crop geometry, so a smooth first crop can cache approval that silently permits visible seams on a later detailed render; conversely, one difficult crop can permanently disable a usable level. Scope the result to the relevant input geometry/content or rerun the probe for each render.

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 2d7cae2. The probe measures how well the halved tile geometry blends its seams. For a given latent shape that geometry is the same on every render, but it is not the same across shapes. The verdict, including the unprobed allowance, is now kept per (latent shape, level). A shape whose working level is already remembered still goes straight to it with no new probe, and a new shape is probed once. Test: test_quality_verdict_is_kept_per_shape.

Comment on lines +326 to +327
tiled_now = bool(getattr(vae, "use_tiling", False))
level_free = memo.get(_key(z)) if tiled_now else None

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 the retry memo for untiled image decodes

When an image VAE starts untiled and recovers through stock or halved tiles, the next decode of the same shape ignores the saved working level because memo is read only when tiled_now is already true; a level-0 recovery is not retained at all. Image loads do not have the video's outer untiled gate to remember this failure, so every subsequent render repeats the known-failing untiled allocation (and often the stock-tile OOM) before reaching the same fallback. Apply the memo to untiled callers too, using the existing free-memory threshold to decide when to retry the larger path.

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 2d7cae2. The working-level memo is now keyed by (shape, tiled) and also records a stock-tile recovery for untiled callers. The next same-shape untiled decode goes straight to the remembered level (tiling on for the attempt, then restored) instead of retrying the untiled allocation that failed. With more than 1.25x the free memory seen at the failure the memo is dropped and the untiled decode is tried again, as before. The video untiled-gate path is unchanged. Test: test_untiled_caller_reuses_the_remembered_level.

Comment on lines +258 to +262
lat = min(
[values[n] // ratio for n in values if n.startswith("tile_sample_min_") and "overlap" not in n]
+ [values[n] for n in values if n.startswith("tile_latent_min_")]
or [MIN_TILE_LATENTS]
)

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 Probe a seam along each asymmetric tile axis

When a VAE exposes different height and width tile sizes, this collapses them to the minimum and uses that scalar for both crop axes. For example, a 16×8-latent level produces a 16×16 crop: the width is tiled, but the height equals its 16-latent tile and therefore has no height seam, even though a full render will have such seams. A clean width comparison can consequently approve a level whose height blending is visibly bad; size each crop axis from its corresponding halved tile dimension.

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 2d7cae2. The probe crop is now sized per axis from that axis's own halved tile: two height tiles on dim -2 and two width tiles on dim -1, with *_size attributes applying to both. Each axis's crop now covers two of its own tiles, so the probe sees a seam on that axis. Test: test_probe_crop_is_sized_per_axis.

…ers, per-axis probe crop; uninstall restores the conv layout

The probe verdict (and the unprobed allowance) is kept per (latent shape, level) instead of per level. The
working-level memo is keyed by (shape, tiled) and also remembers a stock-tile recovery for untiled callers,
which then go straight to it (None now means no memo). The probe crop spans two tiles of each axis's own
halved size. uninstall restores the recorded channels_last(_3d) decode weights.
@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: 2d7cae2ca9

ℹ️ 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 +101 to +105
lat = max(MIN_TILE_LATENTS, base_latent // scale) # the last halving lands on the floor
while lat >= MIN_TILE_LATENTS and not _overlap_ok(lat, lat * ratio, overlap_factor):
lat -= 1
if lat < MIN_TILE_LATENTS or lat >= prev or lat >= base_latent:
return None

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 Search the remaining interval for valid overlap sizes

For overlap factors whose valid tile sizes do not include the 8-latent floor, decrementing only from the nominal halved size can terminate the ladder while a smaller usable tile still exists. For example, with a 32-latent tile and tile_overlap_factor=0.2, level 1 selects 15, but level 2 starts at 8, rejects it, and returns None, even though 10 latents has integral step and blend sizes and could recover the OOM. Search between the floor/nominal target and the preceding tile size before declaring that no further reduction is possible.

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 97628da. Each axis now searches the whole interval for a size the overlap factor tiles exactly. It takes the largest valid size at or below the halved target, and otherwise the smallest valid size above it. The size is always below the previous level's actual size and at least 8 latents. With a 32-latent tile and overlap 0.2 the ladder now goes 32, 15, 10. Test: test_overlap_factor_searches_the_interval_above_the_floor.

Comment on lines +297 to +300
stats["probe_psnr"][level] = None
if lat < UNPROBED_MIN_LATENTS:
return False # not cached: with more memory free the probe may run next time
quality[qkey] = True # a remembered working level must not rerun a probe known to run out of memory

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 Ignore non-tiled axes when applying the unprobed floor

For an asymmetric level where one tile axis is 8 latents but the input already fits within that axis, the only actual seams may be along another axis whose tiles are at least 16 latents. If the untiled probe OOMs, using min(lat_h, lat_w) nevertheless rejects the level as an unsafe 8-latent fallback. For example, an 8×64 latent decoded with 8×16 tiles has no height seam and could be recovered under the documented 16-latent unprobed policy, but this branch fails the render. Compute the cutoff from axes that actually produce seams for the current input.

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 97628da. The 16-latent unprobed floor now only considers axes the current input actually tiles, that is, axes whose latent size exceeds that axis's tile. An 8-latent tile on an axis the input fits in has no seam and no longer blocks the level. If neither axis tiles, the level is allowed. Test: test_unprobed_floor_ignores_an_axis_the_input_fits_in.

@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: 97628da425

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

# The unprobed floor only looks at axes this input actually tiles (an axis it fits in has no seam).
seamed = [n for n, size in ((lat_h, int(z.shape[-2])), (lat_w, int(z.shape[-1]))) if size > n]
lat = min(seamed) if seamed else UNPROBED_MIN_LATENTS
sl = [slice(None)] * z.dim()

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 Limit the seam probe to one batch element

When z contains multiple samples, this crop retains the entire batch, so the untiled two-tile reference can OOM solely because its memory scales with batch size even when the full render would fit using one spatial tile at a time. For a level below UNPROBED_MIN_LATENTS, that probe OOM makes _level_quality_ok reject the level without attempting the recoverable tiled decode. Probe a single batch element (or otherwise avoid multiplying the reference by the render batch), since seam quality can be validated per sample.

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 3fa3473. The probe crop now takes only the first batch element. Seam quality is a property of the tile geometry, validated per sample, so the untiled reference no longer scales with the render batch and cannot run out of memory just because of it. Test: test_probe_crop_takes_one_batch_element.

@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: 3fa34734fa

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

seamed = [n for n, size in ((lat_h, int(z.shape[-2])), (lat_w, int(z.shape[-1]))) if size > n]
lat = min(seamed) if seamed else UNPROBED_MIN_LATENTS
sl = [slice(None)] * z.dim()
sl[0] = slice(0, 1) # one sample: seam quality is per sample, and the untiled reference must not scale with batch

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 Slice batch-aligned arguments with the probe latent

When a batched decode supplies per-sample conditioning, such as LTX-2's positional temb, this reduces z to batch 1 but forwards the original batch-sized args and kwargs to both probe decodes. The conditioning may broadcast the probe back to the full batch—defeating the memory reduction—or raise a batch-shape error, which is non-OOM and aborts the otherwise recoverable retry. Slice tensor arguments whose leading dimension matches the original latent batch alongside z.

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 30b5aa5. The probe decodes a single sample, so every tensor argument or keyword argument whose leading dimension equals the latent's batch (such as LTX-2's positional temb) is now sliced to [:1] for both probe decodes. Other arguments are passed through unchanged. Test: test_probe_slices_batch_sized_args_with_the_latent.

def _attempt(level: int, z: Any, args: tuple, kwargs: dict) -> Any:
prev_tiling = bool(getattr(vae, "use_tiling", False))
current = tile_attrs(vae)
vae._unsloth_vae_oom_halvings = level

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 Mark the stock-tile retry as active

When an untiled decode fails, level 0 is documented and memoized as the stock-tile recovery, but storing 0 here is falsy to both wide-tile wrappers, so they run their wide planner instead of handing off to stock tiling. If the wide attempt OOMs and its internal stock fallback succeeds, the outer retry records level 0 as successful; every later same-shape decode then repeats that known-failing wide allocation before falling back again. Use a separate active marker (or otherwise distinguish level 0 from inactivity) so the memoized stock recovery actually bypasses the wide path.

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 30b5aa5. Every retry attempt, including the level-0 stock-tile retry, now sets a separate _unsloth_vae_oom_active marker that is cleared in the finally, and oom_halving_active() reads that marker. Both wide-tile wrappers (diffusion_vae_tiling, video_ltx2_vae_tiles) call oom_halving_active(self), so they hand off to stock tiling on every retry instead of re-running the wide planner. Tests: test_stock_tile_retry_marks_the_retry_active, test_wide_tile_wrappers_read_the_active_marker.

Comment on lines +2263 to +2264
y = group_norm_act(x, norm, act = act)
state.calls += 1

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 Count only actual fused GroupNorm executions

For an uncovered VAE whose GroupNorm shape is unsupported by _gn_fusable—for example, a non-power-of-two channel count—group_norm_act takes its stock reference fallback, but this still increments state.calls. Calibration therefore treats the fallback as proof that fusion ran, accepts the structural patch, and leaves any planned channels-last-3d relayout in place even though no Triton GroupNorm executes; that layout is explicitly slower on the unfused path. Track whether the fused kernel actually ran and reject or unpatch when every matched norm fell back.

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 30b5aa5. Calibration now counts real fused-kernel executions (kernel_calls, counted only when _gn_fusable holds) separately from fallback calls. When no matched norm ran the kernel during the calibration decode, the structural patch is rejected and unpatched, which also restores the recorded channels-last layout. Test: test_structural_rejected_when_every_norm_falls_back.

…y retry active; structural calibration needs a real kernel run

The probe decodes one sample, so tensor args/kwargs whose leading dim is the latent's batch (LTX-2's temb)
are sliced with it. A separate _unsloth_vae_oom_active marker covers every retry attempt including the
stock-tile one, and oom_halving_active() (used by both wide-tile wrappers) reads it. Structural calibration
counts Triton kernel executions apart from fallback calls and rejects the patch when every matched norm fell
back.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 808c7ab707

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

[skip ci]
# Conflicts:
#	studio/backend/core/inference/video_vae_untiled.py
#	studio/backend/tests/conftest.py
@danielhanchen
danielhanchen merged commit c57c21f into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-vae-oom-retry-structural-fused branch October 20, 2026 21:16
danielhanchen added a commit that referenced this pull request Oct 20, 2026
## Problem


`tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding`
fails on main, so the `Repo tests (CPU, rest)` shard is red on every PR
(for example #14395):

```
AssertionError: 3 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": ['tests/test_grouped_gemm_mixed_tma_device.py:218: read_text()', ...]
AssertionError: 2 file reads in the test trees touch a checked-in file with the platform default encoding, ... ['studio/backend/tests/test_diffusion_vae_oom.py:1726: read_text()', 'tests/test_legacy_block_compile_install.py:15: read_text()']
```

Three test files that merged today read checked-in sources with a bare
`read_text()`:

| File | Reads | Added by |
|---|---|---|
| `tests/test_grouped_gemm_mixed_tma_device.py` | 3 | #14358 |
| `studio/backend/tests/test_diffusion_vae_oom.py` | 1 | #13802 |
| `tests/test_legacy_block_compile_install.py` | 1 | #14398 |

The guard is right: on Windows, `read_text()` decodes with the locale
codec (cp1252), so these break as soon as one of those sources gains a
non-ASCII byte.

## Fix

Pass `encoding = "utf-8"` to the five reads. No other change.

## Verification

- On main: `tests/test_source_read_encoding.py`: 2 failed, 14 passed
(the two failures above).
- With this change: the guard and the two touched `tests/` files pass,
apart from 4 `test_legacy_gate` errors.
- Some failures on this host are the same with and without this change,
so they come from the local environment, not this PR:
- the 4 `test_legacy_gate` setup errors in
`tests/test_legacy_block_compile_install.py`;
- 8 failures in `studio/backend/tests/test_diffusion_vae_oom.py` (102
passed).
danielhanchen added a commit that referenced this pull request Oct 21, 2026
… in the CFG routers, and test fixes (#14420)

## Summary

Follow-up fixes for the recently merged Studio diffusion work: two
runtime fixes (the VAE OOM ladder under a multi-GPU component split, and
bitwise comparison of expanded timesteps in the CFG routers) and five
test fixes. Each change is its own commit.

### 1. VAE OOM step (a) frees only what sits on the VAE's card (#13802
with #13725)

**What was broken.** Under a component split the VAE decodes on a
secondary card while the denoiser stays resident on the primary. When
that decode ran out of memory, `DecodeSession.free_others` reset the
denoiser's CUDA graphs on the primary card and counted that as
"released". The ladder then retried the same untiled decode on the
secondary card, which ran out of memory again before it reached the
tiled rung, and the denoiser lost its captured graphs for nothing.
`_release_groups` had the same problem with resident offload groups on
the primary card. A failed re-pin was also deferred against the VAE's
card instead of the groups' own card.

**Fix.** Graph handles are filtered to the VAE's card, using the card
the graph was recorded on (or its module's card when nothing has been
recorded yet). Resident-group modules are filtered by
`_unsloth_resident_device`. This is the same filtering
`_hook_torchao_resident` and `_move_components` already do with
`_placement(comp, self.device)`. `release_resident_groups` takes an
optional `device` filter. It is only passed when the pipeline has
resident groups on more than one card, so single-card calls are
unchanged. Anything whose card cannot be read is still freed, as before.

**Tests** (`test_diffusion_vae_oom.py`, all fail on main):
- `test_split_vae_oom_leaves_the_other_cards_graphs_alone`: a decode on
cuda:1 with graphs on cuda:0 goes straight from the untiled decode to
the tiled one, and no graph is reset.
- `test_split_vae_oom_still_drops_graphs_on_its_own_card`: only the
cuda:1 handle is reset.
- `test_split_vae_oom_releases_only_groups_on_its_own_card`: groups on
cuda:0 are left alone and nothing is deferred against them. With groups
on both cards, the release is limited to cuda:1.
- `test_release_resident_groups_device_filter`: the new filter releases
only the matching card's groups, and with no filter every card's groups
are released.

### 2. Expanded scalars compare bitwise in the CFG routers (#13725,
#13787)

**What was broken.** `_bitwise_equal` in `diffusion_multigpu.py`
flattens both tensors, calls `contiguous()` and views them as `uint8`.
WanPipeline passes `timestep = t.expand(batch)`. For a one-element
tensor `contiguous()` is a no-op whatever the stride, so the stride-0
timestep reached `view(torch.uint8)`, which raised, and the comparison
returned False for two equal timesteps. #13787 CFG batching uses it
through `_record_template`, `_matches` and the branch merge. On Wan it
missed three times in a row and turned itself off. CFG-parallel's
prediction check uses the same helper.

**Fix.** A small `_as_bytes` helper takes a dense copy only when the
flattened tensor still has a non-unit stride. `_bitwise_equal` and
`_unchanged_since_launch` both use it. Bitwise semantics are unchanged:
equal NaN bits match, and -0.0 and 0.0 do not. The CFG batcher's three
call sites all go through `_bitwise_equal`, so they are covered by the
same fix.

**Tests** (both fail on main):
- `test_bitwise_equal_on_an_expanded_scalar`
(`test_diffusion_multigpu.py`): `torch.tensor(941).expand(1)` against a
clone and a fresh expand, plus NaN, signed zero and
`_unchanged_since_launch`.
- `test_wan_expanded_timesteps_serve_the_second_branch`
(`test_diffusion_cfg_batch.py`): a Wan-style loop that passes
`t.expand(batch)` to each branch. It matches the two-call reference with
4 hits, 0 misses, and batching stays on. On main it gets 0 hits.

### 3. Seeded denoiser cancel test pins the text encoder (#13715)

**What was broken.** On a CUDA host, an unset `text_encoder_quant` also
plans the hosted FP8 Wan text encoder. The load then fetched two
artifacts and
`test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event`
failed its exact single-fetch assertion. It passed only with the GPU
hidden.

**Fix.** The test passes `text_encoder_quant = "off"`, so it checks only
what it is about: the denoiser fetch carries the load's cancel event.

**Test.** Fails on main with a GPU visible and passes after. It passes
both ways with the GPU hidden.

### 4. FLUX.2 FBCache test invalidates the child registry cache (#14401)

**What was broken.** On diffusers 0.39 and 0.40, `enable_cache` does not
drop the child-registry list that an earlier uncached render cached.
`test_fbcache_on_flux2_skips_and_matches_the_full_pass` then failed with
`ValueError: No context is set`. Production already calls
`_invalidate_child_registry_cache` after `enable_cache` in
`apply_step_cache`. Only the test helper skipped it. diffusers 0.41
invalidates the list itself.

**Fix.** The test's `_render` helper calls
`dc._invalidate_child_registry_cache(model)` after `enable_cache`.

**Test.** With diffusers 0.39.0 the test failed before and the whole
file passes after (7 passed). It also passes on the pinned diffusers.

### 5. Stream encode tests skip when diffusers cannot import the Wan VAE
(#14405)

**What was broken.** `pytest.importorskip("diffusers")` succeeds on the
lazy top-level module. The next line, `from diffusers import
AutoencoderKLWan`, can then raise `RuntimeError` (for example with a
broken bitsandbytes), which aborted collection of the whole pytest run.

**Fix.** Catch `ImportError` and `RuntimeError` on those imports and
skip the module, as the other diffusion tests do.

**Test.** In an environment with a broken bitsandbytes, collection
errored before and the module is skipped after. In the Studio
environment all 9 tests still run and pass.

### 6. Multi-GPU planner tests pin the host facts they read (#13725,
#13793)

**What was broken.** On a host with one GPU, 11 tests in
`test_diffusion_multigpu.py` failed. `make_selection` drops ordinals at
or above the real `torch.cuda.device_count()` and cards below the
primary's capability, so `make_selection(0, [0, 1])` returned None on a
one-card machine. An AMD Strix Halo CI runner (one integrated gfx1151)
showed exactly these 11. `test_diffusion_fp8_unit_scale.py` gated on
`get_device_capability() >= (8, 9)`, which passes on ROCm because ROCm
reports the gfx version (gfx1151 gives (11, 5)), and torchao then
refuses fp8 there.

**Fix.** Tests only. The autouse fixture pins the card count and the
capability check (tests that probe those filters still override them),
and the fp8 GPU gate returns False on a HIP torch, matching Studio,
which already declines torchao fp8 on ROCm. New test
`test_two_discrete_rocm_cards_split_like_cuda`: with HIP set and two
cards at capability (11, 0), the planner selects both and splits onto
card 1, as on CUDA.

**Tests.** Spoofed host (HIP + one integrated card, HIP + two discrete
cards, one CUDA card without HIP): 11 failed before, 114 passed after on
each. Normal CPU host: 133 passed, 1 skipped.

### 7. The ROCm APU pool discount applies only to HIP device snapshots
(#14379)

**What was broken.** `_rocm_linux_apu_os_room_outside_pool`
(`diffusion_memory.py`) gave any unified-memory reading the smaller
Linux ROCm APU reserve on a ROCm build, without checking the snapshot's
device. On a ROCm host, a mocked Apple (`mps`) snapshot in
`test_diffusion_unified_load_override.py` got that reserve, so two
refusal tests failed. A real ROCm build never produces an `mps` reading,
so the user impact is close to zero.

**Fix.** The discount now requires a `cuda` device snapshot (`cuda` or
`cuda:N`). `test_flux3_prompt_upsampler.py` also pins
`torch.__version__` in the tests that stand in for a CUDA build (Studio
reads `+rocm` there too) and pins the card count in its warm fixture,
which read the real host.

**Tests.** The new `mps` / `cpu` reserve test fails without the fix and
passes with it. Prompt upsampler: 164 passed on a spoofed APU, two
discrete ROCm cards, two CUDA cards and plain CPU.

## Tests

Base is origin/main and head is this branch. Same host and same Studio
venv (diffusers 0.41 dev, torch 2.13). Failing test IDs were compared,
not counts.

- CPU, GPU hidden: test_diffusion_vae_oom.py,
test_diffusion_vae_oom_faults.py, test_diffusion_measured_placement.py,
test_diffusion_offload_cuda_graph.py, test_diffusion_learned_peaks.py,
test_diffusion_int8_gemm.py, test_video_stream_residency.py,
test_diffusion_offload_prefetch.py,
test_diffusion_small_host_prefetch.py,
test_diffusion_fbcache_mixed_stream.py, test_video_stream_encode.py,
test_diffusion_multigpu.py. Base: 3912 passed, 125 skipped, 0 failed.
Head: 3916 passed (the 4 new tests), 125 skipped, 0 failed. No failing
IDs on either side.
- One GPU visible: test_video_prequant.py. Base: 1 failed
(`test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event`),
85 passed. Head: 86 passed.
- CPU, GPU hidden: test_diffusion_cfg_batch.py,
test_diffusion_multigpu.py, test_diffusion_multigpu_wiring.py,
test_video_multigpu_wiring.py. Base: 128 passed. Head: 130 passed (the 2
new tests). No failures on either side.
- test_diffusion_fbcache_mixed_stream.py on diffusers 0.39.0: 1 failed
before, 7 passed after.

Wan2.1-T2V-1.3B end to end on a Kaggle T4 capped at 7.25 GiB (streamed
offload, fp32, 480x320, 17 frames, 6 steps, guidance 5, seed 1234). Base
and head ran on the two T4s of one kernel, each on its own CPU slice:

| Run | s/step | CFG batch |
|---|---|---|
| base, CFG batching off | 5.96 | not armed |
| base, auto | 8.55 | 0 hits, 3 misses (timestep 941 vs 941), then off |
| head, CFG batching off | 5.58 | not armed |
| head, auto | 5.55 | 2 hits, 0 misses, then off: measured no gain
(batched pair 5.42 s vs plain pair 5.39 s) |

- The 43% slowdown on base is gone. On this streamed T4 placement a
batched pair is no faster than two plain calls, so the batcher's own
timing gate turns it off, as designed.
- The batching-off latents are identical on base and head
(`829b889b587d13f6`), so the plain path is unchanged. The two batched
steps are not bit-exact, as documented for CFG batching.

## Not verified

- CFG-parallel on two real cards: test_diffusion_multigpu_cuda.py needs
two CUDA cards in one process and was skipped.

- No real two-GPU decode that runs out of memory. The split case is
covered by CPU tests that use real `torch.device("cuda", N)` indices
with fake graph handles and resident modules.
- diffusers 0.40.0 was not run. Its source lacks the same invalidation
as 0.39.0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant