Repository navigation
Studio video: keep the untiled decode gate visible under the stream encoder, skip the fp32 VAE rerun on non-finite latents, refuse NaN clips clearly - #15339
Conversation
… skip the fp32 VAE rerun on non-finite latents, refuse NaN clips clearly A streamed Wan render's decode wrapper hid the decode chain, so an untiled OOM was retried tiled by the OOM ladder under the untiled gate (which never recorded it, so every later render ran out of memory again) and the OOM scope was reinstalled above a wrapper the render then dropped. The fp16 VAE's non-finite check reran the decode in fp32 even when the latents were already non-finite: twice the memory (the T4 8 GiB OOM) for the same NaN clip, and every later render stuck in fp32. A NaN clip now fails the render with a clear error instead of PyAV's uint8 dtype error, and the video load passes its logger to the speed layer so those fallbacks are logged. Kill switches: UNSLOTH_STUDIO_VIDEO_STREAM_ENCODE_CHAIN=0, UNSLOTH_VIDEO_VAE_NONFINITE_INPUT_KEEP_FP16=0.
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 |
|
|
…evice index as CUDA in the YaRN load check (#15351) ## Problem Two tests in the `Repo tests (CPU, rest)` shard fail on main itself, so every PR based on it inherits them (seen on #15326 and #15339). Both are test bugs; the product code they guard is fine. **1. `tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding`** ``` Pass encoding = "utf-8": ['tests/test_parallel_general_gloo.py:732: open()'] ``` #15230 added `test_every_whole_model_export_is_guarded`, which reads `unsloth/save.py` with a bare `open(...).read()`. That uses the locale encoding, which on Windows is the ANSI codepage. The read now names `encoding = "utf-8"` and closes the file. **2. `tests/test_yarn_rope_parameters_load.py::test_yarn_reaches_the_model[lang-*]`** ``` RuntimeError: Cannot access accelerator device when none is available. ``` #15214 added this subprocess check. It runs FastLanguageModel on a spoofed CUDA box and sends CUDA tensor allocations to the CPU through an `_is_cuda(device)` helper. The rotary embedding allocates with `device = get_current_device()`, which is a bare index (`0`). The helper called `torch.device(0)`, and on CPU-only torch 2.10 that resolves the index through the accelerator and raises before the YaRN assertion is reached. The `model` cases passed only because that path does not allocate with a bare index. A bare int is now treated as a CUDA ordinal without asking torch, and strings and `torch.device` values go through `torch.device(...)` as before. ## Verification - On main: `test_source_read_encoding.py` 1 failed and `test_yarn_rope_parameters_load.py` 2 failed. The yarn test also fails at #15214's own merge commit (801ba6d), and #15214 never ran a `rest` shard. - With this change: - `test_source_read_encoding.py`: 16 passed - `test_yarn_rope_parameters_load.py`: 5 passed - `test_parallel_general_gloo.py::test_every_whole_model_export_is_guarded`: passed - Sabotage: with FastLanguageModel's `_fold_rope_parameters` call replaced by `rope_scaling = None`, both `lang` cases now fail on the YaRN assertion itself (`{'type': 'linear', 'factor': 4.0, ...}`). Before this change they crashed first, so they could not catch a dropped YaRN.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
…/ uint8 cast or clamp hides them (unslothai#15374) ## Summary Follow-up to unslothai#15339. That PR refuses a Wan clip with NaN / inf frames with a clear `NonFiniteFramesError` in `VideoBackend._encode_mp4`. Two cases never reached that check: 1. Families whose pipelines return PIL frames (`output_type="pil"` by default: `LTX2Pipeline` for LTX-2 / LTX-2.3 / LTX-2.5, `Cosmos3OmniPipeline`, the MiniMax-H3 modular decode step). NaN becomes uint8 0 inside the PIL cast, so Studio saved a black or broken clip without an error. 2. On the np path (Wan, HunyuanVideo-1.5) a lone +inf with no NaN was clamped to 255 by the denormalize before any finiteness check, so it passed silently. MiniMax-H3 also clamps its decode to [0, 1] before `postprocess_video`. ## Changes - `video_frames.finite_video_decode(pipe)`: entered once per render next to the decode-phase wrapper. It installs a `video_finite_decode` layer on `pipe.vae.decode` through `decode_layers.wrap` / `unwrap`, and calls `diffusion_vae_oom.ensure_outermost` after each, so the rule that every decode rewrap re-asserts the OOM scope still holds. The layer has no below-scope marker, so `_scope_intact` stays true, and the scope is put back exactly when the render ends. The layer sits above the load-time decode wrappers, so the fp16 decode's fp32 rerun has already happened. It checks the decoded pixels on their device before any pipeline clamp or cast, and handles tuple outputs and `DecoderOutput.sample` (Cosmos3). - `uint8_video_frames` now also checks the float clip handed to `postprocess_video` (any output type), before the denormalize clamp and the PIL / uint8 conversion. - Both raise the existing `NonFiniteFramesError` / `NON_FINITE_FRAMES_MSG`, which `video_failure_detail` already maps to the user-facing message. - The check is `torch.isfinite(...).all()` on the device tensor, reduced in frame slices (16M elements per bool temporary) with one host sync. There is no host copy, and the output object is returned unchanged. - Kill switch: `UNSLOTH_VIDEO_NONFINITE_CHECK=0` turns off both new checks. The encoder check from unslothai#15339 still runs. ## Tests New `studio/backend/tests/test_video_nonfinite_every_family.py` replays the decode + postprocess sequence of each pipeline shape (Wan np, LTX-2 pil, Cosmos3 `DecoderOutput` pil, MiniMax-H3 clamp-then-pil): - NaN, +inf and -inf are refused with the same message for every shape (12 cases), and so are NaN / +inf at `postprocess_video` for np and pil. - An inf in the last frame of a clip is still found when the check runs over several slices. - Finite clips are bit-identical to the output with the check off (uint8 tensor equality on np, per-frame PIL equality on pil). - The decode slot is restored, both when it came from the class and when it was an instance override. - With the kill switch set, nothing is wrapped and nothing is refused. - With the OOM ladder and scope installed on a VAE, the scope stays intact while the layer is active and is restored exactly afterwards (finite and NaN cases). On `origin/main` 20 of the first 28 new tests fail: all refusal cases, the slicing case, the slot-restore cases and the render-stack check. On this branch all pass. `test_video_frames.py::test_out_of_range_takes_the_original_postprocess[nan-*]` now sets the kill switch, because NaN is refused by default. Decode and stream suites (`test_diffusion_vae_oom.py`, `test_diffusion_vae_oom_faults.py`, `test_video_decode_oom_retry.py`, `test_video_frames.py`, `test_video_nonfinite_every_family.py`, `test_video_stream_encode.py`, `test_video_stream_residency.py`): - merge base 975e864, without the new file: 2 failed, 3532 passed, 10 skipped - this branch: 2 failed, 3562 passed, 10 skipped (the 30 new tests) The same two tests fail on both sides and are unrelated to this change: `test_execution_device_resolves_the_card_while_a_component_waits_on_the_host` and `test_a_compiled_decode_runs_the_chunk_hook_as_one_eager_island[cpu]`.
…lothai#15394) ## Summary The MiniMax-H3 native route (stable-diffusion.cpp sd-server / sd-cli) now refuses a NaN render with the same `NonFiniteFramesError` message the Diffusers path uses (unslothai#15339, unslothai#15374), instead of saving a black clip. The check is behind the existing `UNSLOTH_VIDEO_NONFINITE_CHECK` kill switch. ## Why a check on the returned clip sd.cpp has no NaN / inf check of its own. A NaN render logs nothing unusual, exits 0, and writes the clip. Studio only gets an encoded container back (MJPEG + PCM in AVI from sd-server, VP8 + PCM in WebM from sd-cli), so there is no float clip to check. What a NaN render turns into: - **The VAE tails clamp on the device.** Video is clamped to [0, 1], audio to [-1, 1]. - **ggml's clamp maps NaN differently per backend.** On CUDA (`fminf` / `fmaxf`) NaN becomes the lower bound. On the CPU backend (`MIN` / `MAX` macros) it becomes the upper bound. This was measured against ggml on both backends. - **The whole clip is affected.** The H3 DiT attends text, video and audio tokens jointly, so a NaN there reaches every token. Every frame comes out flat black (or white on CPU), and the PCM soundtrack is one constant full-scale level (-32767 / 32767). A flat-frame check alone is not safe. A legitimate night scene a few levels above black decodes almost flat after the lossy MJPEG / VP8 encode. The soundtrack is what tells the two apart: no generated soundtrack is a single full-scale DC level for the whole clip. ## Change - **`h3_native_clip_is_nan_render(path)`** (video_minimax_h3.py, torch-free). It flags a clip only when it has an audio track whose every sample is one full-scale level, and every frame is exactly black (or white). It reads the audio first, so a normal clip costs one PCM decode. - **`_generate_h3_native`** runs it before `inspect_video`, which covers both the server and the CLI routes. A match raises `NonFiniteFramesError(NON_FINITE_FRAMES_MSG)`, which `video_failure_detail` already maps for the UI. A probe that cannot read the clip never fails the render. These clips are always kept: flat black with real or silent audio, a dark clip, a clip without audio, and real frames over a broken soundtrack. ## Tests `tests/test_h3_native_nonfinite.py` writes clips the way sd.cpp writes them, in both containers. - On main: 5 failed, 18 passed. The 4 NaN fingerprints and the end-to-end refusal fail; the keep cases pass. - On this branch, all pass. - `pytest -n 4` over the new file, test_video_backend.py, test_video_static_skip.py, tests/test_sd_cpp*.py and tests/test_h3_native_*.py: 2205 passed, 1 skipped. ## Limits - **Not caught:** a NaN only in the video VAE (flat frames over real audio look like a real black clip, so it is kept), a partial NaN such as one bad tile, and a render without audio. A finiteness check inside stable-diffusion.cpp would be the complete fix. - **No full H3 NaN render was run.** The fingerprint comes from the sd.cpp source, ggml clamp behaviour measured on CPU and CUDA, and clips written by sd.cpp's own container writers.
Summary
A Wan2.1-T2V-1.3B render on a Kaggle T4 at a forced 8 GiB budget failed at export with
ValueError: Expected numpy array with dtype uint8 but got float32. The log showed an untiled decode, thendecode ran out of memory; retrying tiled at stock tile sizes, thenvideo.stream_encode: fallback (decoder restarted).The decode retry did not corrupt the clip. Rebuilding Studio's real Wan decode stack around the real Wan2.1 VAE (fp16 decode, fused VAE kernels, untiled gate, OOM ladder and scope, stream encoder) reproduces that log sequence line for line, but only when the latents reaching the VAE are non-finite:
_video_vae_half_decodesees the non-finite output, moves the decoder to fp32 for good, and reruns the decode untiled. That rerun is thedecoder restartedline. The warning it logs was dropped, because the video load calledrun_speed_layerwithout a logger.With finite latents, every OOM retry path returns finite frames close to an untiled render.
Two more bugs came up along the way. The stream encoder's per-render
decodewrapper had no__wrapped__, which hid the decode chain:diffusion_vae_oomcould not find the untiled-when-fits gate, so the ladder retried tiled underneath it. The gate never recorded the OOM, so every later render ran out of memory again.Changes
video_stream_encode.py: the Wan and H3 sessiondecodewrappers expose__wrapped__. The untiled gate now handles an untiled OOM during a streamed render, and the scope stays installed. Kill switch:UNSLOTH_STUDIO_VIDEO_STREAM_ENCODE_CHAIN=0.diffusion_speed.py(_video_vae_half_decode): when the latents themselves are non-finite, the decoder stays in fp16 and does not rerun in fp32 (fp32 cannot make NaN inputs finite). The finiteness check runs only on the branch where the fp16 output is already non-finite. A non-finite fp16 output from finite latents still reruns in fp32, as before. Kill switch:UNSLOTH_VIDEO_VAE_NONFINITE_INPUT_KEEP_FP16=0.video_frames.py/video.py:_encode_mp4refuses float frames that hold NaN or inf withNonFiniteFramesError.video_failure_detailmaps it to a fixed message ("The decoded video holds NaN or infinite values, so it was not saved."). Before this change, every encoder path ended in PyAV's dtype error on such frames. Finite frames are untouched, and frames are never clamped.video.py: the video load passes its logger torun_speed_layer, as the H3 path already does, so speed-layer warnings are logged.Results
Real Wan2.1-T2V-1.3B VAE with Studio's decode stack, 480x832, 33 frames, on a local B200 with a per-process memory cap:
torch.equal), streamvalidretrying tiled at stock tile sizes; the next render OOMs againuntiled decode ran out of memory; decoding tiled; the next render goes tiled without an OOMdecoder restarted), OOM, tiled fp32, NaN float32 clip; export crashes in PyAVTests
tests/test_video_decode_oom_retry.py, 10 tests:test_video_stream_encode,test_video_vae_untiled,test_diffusion_vae_oom*,test_video_frames,test_diffusion_speed,test_diffusion_autoopt_*,test_video_vae_fp16_decode,test_video_encode,test_video_nvenc,test_video_stream_residency,test_vae_channels_last_3d,test_video_vae_bf16_decode_rocm): 3872 passed, 2 failed.test_a_compiled_decode_runs_the_chunk_hook_as_one_eager_island[cpu]andtest_execution_device_resolves_the_card_while_a_component_waits_on_the_host. Both fail the same way on main (a diffuserspipeline_utilsimport error on this host).Limits
video.wan_fused: fused fp16 modulation did not match the stock block, which is what a NaN in the stock block's output would cause. This points at the denoiser on that load, not the decode, but it has not been reproduced.diffusion_vae_fp16.py) has the same fp32-rerun-on-NaN-input pattern. It is not changed here.