Skip to content

Studio video: refuse NaN / inf decodes for every family before a PIL / uint8 cast or clamp hides them - #15374

Merged
danielhanchen merged 4 commits into
mainfrom
studio-video-nonfinite-every-family
Oct 26, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-video-nonfinite-every-family

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Follow-up to #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 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 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].

…/ uint8 cast or clamp hides them

PIL-output families (LTX-2, LTX-2.3, LTX-2.5, Cosmos3, MiniMax-H3) turned NaN
frames into black uint8 pixels, and the np path clamped a lone +inf to 255,
so neither reached the encoder's finiteness check. The render now checks the
float clip on its device at vae.decode (before MiniMax-H3's clamp) and at
postprocess_video (before denormalize / PIL / uint8), raising the same
NonFiniteFramesError. Finite clips are returned untouched.
UNSLOTH_VIDEO_NONFINITE_CHECK=0 turns the new checks off.
…e OOM scope contract

finite_video_decode reassigned vae.decode per render, which broke the rewrap
contract (every .decode rewrap re-asserts the OOM scope). It now goes through
decode_layers.wrap / unwrap and calls ensure_outermost after each, carrying no
below-scope marker so _scope_intact still holds; the scope is put back exactly
when the render ends.
@danielhanchen danielhanchen self-assigned this Oct 26, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T13:26:24.971107Z 5808068 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 5808068c55

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen added a commit that referenced this pull request Oct 26, 2026
## Problem


`tests/security/test_lint_risky_loaders.py::test_the_tree_matches_the_baseline`
and the `Source lint` risky-loader step fail on main since #15353, so
every PR based on it inherits the failure (#15374 today):

```
1 risky loader call site(s) not in the baseline:
  unsloth/models/fsdp2_save.py:695  [unsafe-deserialize] pickle.loads
```

#15353 added `_share_from_writer`. The export's writer rank pickles a
small result into the job's default c10d store: the RAM refusal string,
or `("ok", run())` / `("error", message)`. The other ranks wait on that
key and unpickle it.

## Product or test

Neither is wrong; the call site just was not recorded. The bytes come
only from a peer rank of the same job, through the job's own c10d store,
under an `unsloth_fsdp2_export_*` key. Anyone who can write that store
already controls the job's collectives. A format change would be a
product change: `run()` returns whatever the export returns, so JSON
would need its own handling for each exporter. The lint's prescribed
path for a trusted input is a reviewed baseline entry, and that is what
this does.

## Fix

- `python scripts/lint_risky_loaders.py --update`, which added exactly
one entry (`unsloth/models/fsdp2_save.py`, `pickle.loads`, `count: 1`)
and changed nothing else.
- Its "REVIEW ME" reason replaced with why the input is trusted.

## Verification

- `python scripts/lint_risky_loaders.py`: `ok: 109 risky loader call
site(s), all recorded` (failed on main).
- `tests/security/test_lint_risky_loaders.py`: 46 passed.
- Sabotage: adding a second `pickle.loads` to `fsdp2_save.py` is still
reported as not in the baseline, because the entry is pinned to `count:
1`.
@danielhanchen
danielhanchen merged commit ad79849 into main Oct 26, 2026
15 of 39 checks passed
@danielhanchen
danielhanchen deleted the studio-video-nonfinite-every-family branch October 26, 2026 15:14
CSEliot pushed a commit to CSEliot/unsloth-eliot that referenced this pull request Oct 26, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant