Repository navigation
Studio: offload-first retry for an OOM VAE decode, fuse GroupNorm+SiLU on uncovered VAEs by structure - #13802
Conversation
… 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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| inner = vae.__dict__.pop("_unsloth_vae_structural_inner", None) | ||
| if inner is not None and getattr(vae.__dict__.get("_decode"), "_unsloth_vae_fused", False): |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| tiled = _decoded(_attempt(level, crop, args, kwargs)).float() | ||
| mse = float((tiled - ref).pow(2).mean()) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if lat < MIN_TILE_LATENTS or lat >= prev or lat >= base_latent: | ||
| return None # under the floor, or no smaller than the previous level |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| _release_cache(z, vae) | ||
| stats["probe_psnr"][level] = None | ||
| return lat >= UNPROBED_MIN_LATENTS |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if level in quality: | ||
| return quality[level] |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| tiled_now = bool(getattr(vae, "use_tiling", False)) | ||
| level_free = memo.get(_key(z)) if tiled_now else None |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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] | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…verlap factor allows, unprobed floor only on axes the input tiles
|
@codex review |
There was a problem hiding this comment.
💡 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() |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| y = group_norm_act(x, norm, act = act) | ||
| state.calls += 1 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
[skip ci]
# Conflicts: # studio/backend/core/inference/video_vae_untiled.py # studio/backend/tests/conftest.py
… not installed [skip ci]
## 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).
… 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.
Problem
A VAE decode that runs out of memory fails the whole render after the denoiser has finished.
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_untiledfor video), so this is only the runtime fallback for a misprediction: another process taking VRAM mid-render, fragmentation, an uncalibrated family.Fused VAE kernels only engage on a fixed list of classes.
diffusion_vae_fusedfuses GroupNorm+SiLU for AutoencoderKL, FLUX.2, Qwen-Image, Wan and LTX-2. Any other diffusers VAE, such as HunyuanImage-2.1'sAutoencoderKLHunyuanImage, decodes fully unfused.Change
1. Offload-first retry on a decode OOM (new
diffusion_vae_oom.py, wired indiffusion.pyandvideo.py)The retry wraps
_decodeon 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:
diffusion_cuda_graph.reset_all, as both backends already do on any OOM; they re-capture on the next step);release_resident_groups, the path an oversized request uses);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:
_hf_hookwhoseexecution_devicekeepsDiffusionPipeline._execution_deviceon 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.uninstallremoves the_decodewrapper 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).torch.compile: the_decodewrapper 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 outermostdecodelayer, 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_decodeladder (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 rewrapsvae.decodeafter 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.tryand nothing else.VAE.decode(comfy/sd.py) callsload_models_gpu([vae], memory_required=estimate)before decoding, andfree_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 withdecode_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 nextload_models_gpu.UNSLOTH_VAE_OOM_RETRY=0. Counters and timings are onvae._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:nn.SiLU.UNSLOTH_VAE_FUSED_STRUCTURAL=0.Results
Decode speed (structural fusion), B200, bf16, median of 5 decodes from a real encoded latent:
UNSLOTH_VAE_FUSED_STRUCTURAL_CACHE=0turns the cache off.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.
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.
Tests
tests/test_diffusion_vae_oom.pycovers: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_decodeoverride under a laterdecodewrapper, 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.release_resident_groups(29 files): 4123 passed, 179 skipped.test_diffusion_vae_oom.pyalone: 46 passed, 2 CUDA-only skips.Not covered
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._hf_hookwhoseexecution_deviceis the card, so_execution_deviceresolves the card (tested on a tiny diffusers pipeline); not exercised in a full Studio render at a real limit.Tests (addendum)
main(one conflict inrelease_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 byrestore).test_vae_restore_oom_keeps_offload_hooks_and_retriesandtest_real_vae_offload_hooks_round_tripuse 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.test_diffusion_vae_oom.py+test_diffusion_vae_oom_faults.py3462 passed, 2 skipped (CUDA-only), and the two above, which errored before and now skip.