Skip to content

[diffusion] Encode the MP4 while the VAE decodes (MiniMax-H3, Wan) - #41819

Merged
mickqian merged 25 commits into
mainfrom
mick/diffusion-h3-stream-encode
Oct 8, 2026
Merged

mickqian merged 25 commits into
mainfrom
mick/diffusion-h3-stream-encode

Conversation

@mickqian

@mickqian mickqian commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #41797 (the encoder takes the per-request x264_preset from it). It also carries #41834, which applies the same streaming to Wan.

Motivation

The MiniMax-H3 video VAE decodes a clip in temporal chunks — seven for a 5 s clip — and writes each chunk's finished frames into the output buffer in order. The MP4 was only encoded afterwards, in the worker's save step, so x264 spent about 0.5 s on the CPU after the GPU had finished, with the GPU idle. Benchmarks that time a request to the last byte of the MP4 at batch size 1 count all of it.

The Wan VAE is a better fit for the same idea. Its feature-cache decode runs the decoder on one latent frame at a time, and the causal cache only carries context forward, so each step's frames (one, then four per latent frame) are final as soon as they come out. Wan requests also encoded the whole clip only after the decode.

Modifications

Encoder and MiniMax-H3

  • CudaVideoEncoder (entrypoints/utils.py) takes [3, t, H, W] CUDA frames in pieces. write() queues the uint8 conversion on the current stream and returns; a writer thread copies each chunk into registered host memory and pipes it to ffmpeg. The one-shot direct save is now a single write() through the same encoder, so both paths run the same ffmpeg command on the same bytes and produce the same file.
  • Frames now go into the pipe with write() instead of sendfile(). sendfile() from a memfd into a pipe lends the pipe the staging buffer's pages rather than copying them, so reusing the buffer before ffmpeg has read them changes frames that were already sent. Written one frame at a time, frames 0-2 came out carrying frame 3's pixels. The old one-shot loop got away with it because the next chunk's GPU conversion ran before the buffer was reused, which gave ffmpeg time to drain the at most 64 KB left in the pipe. At H3 size its output matched a file-input reference encode in 3 of 3 runs, but only because of that timing.
  • decode_base / decode_temporal in the H3 VAE take an on_frames callback. It receives every output frame once, in order, as soon as the frame is final. Temporal chunks are the unit, whether or not the decoder tiles spatially.
  • MiniMaxH3DecodingStage decodes the audio first, because ffmpeg needs the soundtrack when it starts, and declares its component uses in that order. The streaming path runs only for requests returned as a file path, on the replica's output rank, with no frame interpolation, no upscaling and no torch.compile'd VAE. On that path the stage applies the unchanged per-frame post-processing to each run of frames, feeds it to the encoder, and returns output_file_paths without the frames, so the worker has nothing left to save. If encoding fails at any point, the partial file is removed and the stage returns the frames for the worker to save as before.

Shared

  • stages/encode_while_decoding.py: the encoder feed (EncodeWhileDecoding) and the eligibility rules (streamed_video_output_path) that the H3 stage started with, moved unchanged. The H3 stage and the generic DecodingStage both import them, so both stream under exactly the same rules and fall back the same way.

Wan

  • AutoencoderKLWan.decode(on_frames=...) hands the callback a finished copy of each latent step's frames: unpatchify, float, then clamp, as decode applies to the whole clip. It still concatenates the raw chunks and finishes them at the end, so the returned frames are unchanged.
    • The tiled and whole-clip paths, used when use_feature_cache=False, only finish frames at the end, so the callback then receives the whole clip once. No registered Wan config takes those paths.
    • Under spatial-parallel decode, each step all-gathers to full height before the callback. That follows from the code, but it has not been run on more than one GPU.
  • ParallelTiledVAE declares supports_decode_on_frames = False and AutoencoderKLWan sets it to True.
  • The generic DecodingStage streams only when the request meets the same rules as H3, the stage's own decode and forward are not overridden, the VAE is a ParallelTiledVAE that declares supports_decode_on_frames, and no trajectory is decoded.
  • Stages that override decode, such as the SANA-WM refiner, keep their signature: the generic forward passes on_frames only when it streams.

Accuracy Tests

MiniMax-H3:

  • New test/registered/unit/diffusion/test_minimax_h3_streamed_encode.py:
    • The callback sees the decoded video exactly once, in order, and the frames are final when handed out, with the streaming temporal concat both on and off.
    • Trimmed decodes reject the callback.
    • Writing a clip in uneven pieces produces the same MP4 bytes as the one-shot save, with and without audio, including a size that needs the macroblock scale filter.
    • Two encoders can run concurrently.
    • A failed encode leaves no file behind.
  • test_output_saving.py and test_video_encode_preset.py pass unchanged.
  • End to end, every request in the runs below produced the same MP4 (same md5) with and without streaming.

Wan:

  • test_wan_vae_on_frames.py (CPU, tiny Wan2.1 and Wan2.2 configs): the pieces concatenate to exactly what decode returns, and passing the callback does not change the output.
  • test_wan_streamed_encode.py (CUDA): runs the real DecodingStage.decode and encoder feed, and checks that the streamed MP4 is byte-identical to the one-shot save, for Wan2.1 under bf16 autocast at a size that is not a multiple of 16 and for Wan2.2 in fp32 with 2x2 patches. It also checks the eligibility rules. Changing the streamed frames by 1% makes the byte comparison fail.
  • sana_wm/test_pipeline_config.py: the SANA-WM refiner, which overrides decode, still decodes through its own override.
  • On 1x H200 at the branch head: both streamed-encode tests, test_wan_vae_on_frames.py, test_output_saving.py, test_video_encode_preset.py, test_webui.py and sana_wm/test_pipeline_config.py, 125 passed.

Speed Tests

MiniMax-H3:

MiniMax-H3, --model-variant fl2va --performance-mode speed --enable-torch-compile false, t2va, 1344x768, 5 s (124 frames). One server per setup, with the two modes interleaved on the same server by a toggle that exists only in the test tree. Time is measured from POST /v1/videos to the last byte of GET /v1/videos/{id}/content.

Setup Steps Encode while decoding Encode after decoding Saved
1x H200 4 21.616 s 21.958 s 0.342 s
2x H200, TP 2 4 11.450 s 11.808 s 0.358 s
2x H200, TP 2 20 58.334 s 58.690 s 0.356 s

Medians of 3 for 4 steps, means of 2 for 20 steps; spread within a mode was at most 0.09 s.

  • The decoding stage now includes the encoder's tail: 5.006 s against 4.861 s on one GPU, and 2.604 s against 2.460 s on two. Most of that tail is x264's lookahead draining after the last frames arrive. The roughly 0.5 s save step that followed the decode is gone.
  • Peak memory per request on 2x H200 went from 72,130 MB to 70,664 MB, because the stage no longer materializes the whole video in float32 when it streams.

Wan, 2 denoising steps, fixed seed, time from POST /v1/videos to the last byte of the content:

Workload GPU Encode after decoding Encode while decoding Saved
Wan2.1 T2V 1.3B, 832x480, 81 frames 1x B200 1.955 s 1.757 s 0.198 s
Wan2.2 TI2V 5B, 1280x704, 121 frames 1x B200 6.266 s 5.827 s 0.439 s
Wan2.1 T2V 1.3B, 832x480, 81 frames 1x H200 3.382 s 3.202 s 0.180 s
  • B200: the two modes interleaved on one server (off, on, on, off, four times), medians. H200: main (cae69be) against this branch, A B A with five requests each after a warmup, medians; all 18 MP4s had the same md5.
  • DecodingStage now includes the encoder's tail (H200: 1.50 s to 1.77 s) and the worker's save step disappears, so CI perf baselines will see DecodingStage rise while end-to-end latency drops.
  • Peak reserved memory on B200: 11,936 to 11,716 MB for Wan2.1, 33,420 to 30,756 MB for Wan2.2.
  • A 25-frame Wan2.2 clip goes from 1.380 s to 1.302 s: x264 holds back its look-ahead, so short clips gain less.

🤖 Generated with Claude Code


CI States

Latest PR Test (Base): ✅ Run #37698310254
Latest PR Test (Extra): ❌ Run #37698310147
Latest PR Test (AMD ROCm 10): ⏳ Run #37698310273

mickqian and others added 2 commits September 30, 2026 09:24
The MP4 encoder preset was a module constant (fast), so neither users nor
benchmarks could change it: a latency-bound deployment could not trade file
size for encode time, and a comparison could not pin the same encoder
settings on every system.

Requests now take x264_preset: in a JSON body, as a multipart form field,
and as --x264-preset for sglang generate. It reaches all three libx264 call
sites (the direct CUDA pipe, the single-pass video and audio encode, and
the imageio fallback). Unset keeps fast, unknown values are rejected with
HTTP 400, and grouped outputs must share it like output_compression. The
HTTP /generate fallback save now also passes output_compression, which it
used to drop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The H3 video VAE decodes a clip in temporal chunks and writes each chunk's
finished frames into the output buffer in order, but the MP4 was only encoded
after the whole decode, in the worker's save step. For requests that are
returned as a file path, the decoding stage now hands each finished run of
frames to the encoder as soon as the VAE writes it, so x264 encodes on the CPU
while the GPU decodes the rest.

- entrypoints/utils.py: CudaVideoEncoder takes [3, t, H, W] CUDA frames in
  pieces. write() queues the uint8 conversion and returns; a writer thread
  stages each chunk in registered host memory and pipes it to ffmpeg. The
  one-shot direct save is now a single write through the same encoder, so both
  paths run the same command on the same bytes and write the same file.
  Frames go into the pipe with write() instead of sendfile(): sendfile lends
  the pipe the staging buffer's pages, so reusing the buffer before ffmpeg
  reads them corrupts earlier frames.
- klvae.py: decode_base/decode_temporal take an on_frames callback that
  receives every output frame once, in order, as soon as it is final.
- MiniMaxH3DecodingStage decodes the audio first, since ffmpeg takes the
  soundtrack when it starts, and declares its component uses in that order.
  On the output rank of a file-path request it streams the post-processed
  frames to the encoder and returns the saved path instead of the frames; if
  encoding fails it falls back to returning the frames for the worker to save.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the diffusion SGLang Diffusion label Sep 30, 2026
kevin-mii added a commit to kevin-mii/sglang that referenced this pull request Sep 30, 2026
sgl-project#41819 encodes the H3 MP4 while the VAE decodes through the same temporal
chunk writer, and also fixes the sendfile page-lending hazard in the direct
save. This PR keeps the other optimizations; the GB300 table notes it was
measured with streaming on. The V2 overlay pin moves to the revision without
the stray __pycache__.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mickqian mickqian added the run-ci CI: run the baseline test suite on this PR label Sep 30, 2026
mickqian and others added 2 commits September 30, 2026 12:10
AutoencoderKLWan decodes a clip one latent frame at a time through its causal
feature cache, and each call's frames are final as soon as the decoder returns
them, but the MP4 was only encoded after the whole decode, in the worker's save
step. For requests that are returned as a file path, the generic DecodingStage
now hands each latent frame's pixels to the encoder as the VAE produces them, so
x264 encodes on the CPU while the GPU decodes the rest.

- encode_while_decoding.py: the H3 stage's encoder feed and its eligibility
  rules move here unchanged, so both stages stream under the same conditions
  (one-sample file-path video request, no frame interpolation or upscaling, no
  torch.compile, the base post_decoding, CUDA, the replica's output rank) and
  fall back to returning the frames if encoding fails.
- wanvae.py: decode takes an on_frames callback that receives every returned
  frame once, in order, as soon as it is final: per latent frame on the
  feature-cache path (full height under spatial-parallel decode as well), and
  once at the end on the tiled and whole-clip paths, which only finish frames
  when they merge. The returned frames and their memory are unchanged.
- DecodingStage.decode hands the callback the same [0, 1] frames it returns.
  forward streams only when the stage's own decode and forward run, the VAE
  declares supports_decode_on_frames and no trajectory is decoded, and then
  returns the saved path instead of the frames.

Interleaved A/B in one server on B200 (2 steps): Wan2.1 T2V 1.3B 832x480x81
e2e 1.955 -> 1.757 s, Wan2.2 TI2V 5B 1280x704x121 6.266 -> 5.827 s, with the
same MP4 bytes in both modes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The WebUI save now forwards request.x264_preset, which the fake request in
the lifecycle test did not have. Give it a non-default preset and check that
it reaches save_outputs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mickqian and others added 5 commits September 30, 2026 14:12
…attr

The generic DecodingStage asked getattr(self.vae, "supports_decode_on_frames",
False), which .claude/rules/no-getattr-defensive.md rules out. Declare the
capability as False on ParallelTiledVAE, which AutoencoderKLWan overrides, and
narrow with isinstance so a VAE outside that hierarchy still never streams.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mickqian mickqian changed the title [diffusion] H3: encode the MP4 while the VAE decodes [diffusion] Encode the MP4 while the VAE decodes (MiniMax-H3, Wan) Sep 30, 2026
@JackZeng0208

Copy link
Copy Markdown
Contributor

I also meet the similar problem while supporting Cosmos 3 Edge on SGLang-Omni (sglang-omni/pr#2017). With layerwise offload, the last frame of a conversion chunk came out wrong

Base automatically changed from mick/diffusion-video-encode-preset to main October 4, 2026 08:22
@mickqian mickqian added release-highlight Candidate PR for release note highlight highest-priority CI: all three control labels, plus never batch-cancelled or stale-closed labels Oct 5, 2026
Mick and others added 3 commits October 7, 2026 23:35
Picks up #42958, which warms CI cases up at the request's quality level.
Without it the LTX-2 two-stage cases on the 2-GPU partition run their timed
request on a path warmup never touched and exceed their refinement limits;
main itself fails the same way.

The two streamed-encode tests move to python/sglang/multimodal_gen/test/unit/
with the rest of the diffusion unit tests (#42706), dropping their
register_cuda_ci call as the moved files did: that directory is collected
whole, so new files need no registration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the streamed encode

Encoding the MP4 while the VAE decodes moves the encode inside
DecodingStage, and with it inside e2e (which is the sum of the stages).
On main the encode ran after the last stage, so neither number covered it:
the 1.07-1.10 s DecodingStage baselines and the e2e baselines measured less
work than the request does. The stage timers also do not synchronize, so
the old DecodingStage figure was mostly the CPU-side launch (0.30 s against
1.48 s of GPU decode on a synchronized H200 run); the encoder's close() now
waits for the decode inside the stage, which is the first time this stage
reports what it costs.

Whole requests are not slower: same-process A/B with the streamed encode
off and on gives 1.817 s against 1.729 s for decode plus encode, and the
fastwan request total (MP4 written) is 3.29 s against 3.55 s on main.

New values are the medians of the 7 retries of each case on H100, in the
first run with #42958 merged (37645482900):

  fastwan2_2_ti2v_5b  DecodingStage 1073.10 -> 2173.40, e2e 2444.17 -> 3073.51
  wan2_2_ti2v_5b      DecodingStage 1098.67 -> 2172.17, e2e 14853.56 -> 15599.56

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The streamed-encode tests moved into python/sglang/multimodal_gen/test/unit/
in the main merge, and dropped the register_cuda_ci call that kept them on
CUDA runners. ROCm collects every flat test file in that directory, so
test_only_file_path_video_requests_stream now runs on MI300, where
streamed_video_output_path declines by design (it requires
current_platform.is_cuda()):

  AssertionError: None is not an instance of <class '...EncodeWhileDecoding'>

Skip that one test off the CUDA platform. The rest of both files run and
pass on ROCm (the encoder and the frame hand-off work there), so they keep
their coverage. On an H200 both files still run in full: 8 passed, 22
subtests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mickqian
mickqian merged commit 9101e89 into main Oct 8, 2026
203 of 220 checks passed
@mickqian
mickqian deleted the mick/diffusion-h3-stream-encode branch October 8, 2026 01:01
mickqian pushed a commit that referenced this pull request Oct 24, 2026
The MP4 encode now runs inside Cosmos3DecodingStage instead of after it,
outside the timed window, so the stage and the stage-sum e2e grow while the
request gets faster: "Pixel data generated" (decode plus save) is 0.48 s
here against 0.72-1.00 s on other PRs' runs of the same case. Seeded from
the 7 CI attempts on f86dd52 (medians: stage 211.21 ms, e2e 476.39 ms),
as #41819 did for Wan and MiniMax-H3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

diffusion SGLang Diffusion highest-priority CI: all three control labels, plus never batch-cancelled or stale-closed release-highlight Candidate PR for release note highlight run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants