Repository navigation
[diffusion] Encode the MP4 while the VAE decodes (MiniMax-H3, Wan) - #41819
Merged
Merged
Conversation
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]>
mickqian
requested review from
AgainstEntropy,
BBuf,
HaiShaw,
kevin-mii,
niehen6174,
ping1jing2 and
yichiche
as code owners
September 30, 2026 03:20
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]>
5 tasks done
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
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 |
2 of 5 tasks
This was referenced Oct 7, 2026
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]>
Merged
3 of 5 tasks
3 of 5 tasks
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #41797 (the encoder takes the per-request
x264_presetfrom 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 singlewrite()through the same encoder, so both paths run the same ffmpeg command on the same bytes and produce the same file.write()instead ofsendfile().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_temporalin the H3 VAE take anon_framescallback. 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.MiniMaxH3DecodingStagedecodes 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 returnsoutput_file_pathswithout 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 genericDecodingStageboth 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, asdecodeapplies to the whole clip. It still concatenates the raw chunks and finishes them at the end, so the returned frames are unchanged.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.ParallelTiledVAEdeclaressupports_decode_on_frames = FalseandAutoencoderKLWansets it to True.DecodingStagestreams only when the request meets the same rules as H3, the stage's owndecodeandforwardare not overridden, the VAE is aParallelTiledVAEthat declaressupports_decode_on_frames, and no trajectory is decoded.decode, such as the SANA-WM refiner, keep their signature: the genericforwardpasseson_framesonly when it streams.Accuracy Tests
MiniMax-H3:
test/registered/unit/diffusion/test_minimax_h3_streamed_encode.py:test_output_saving.pyandtest_video_encode_preset.pypass unchanged.Wan:
test_wan_vae_on_frames.py(CPU, tiny Wan2.1 and Wan2.2 configs): the pieces concatenate to exactly whatdecodereturns, and passing the callback does not change the output.test_wan_streamed_encode.py(CUDA): runs the realDecodingStage.decodeand 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 overridesdecode, still decodes through its own override.test_wan_vae_on_frames.py,test_output_saving.py,test_video_encode_preset.py,test_webui.pyandsana_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 fromPOST /v1/videosto the last byte ofGET /v1/videos/{id}/content.Medians of 3 for 4 steps, means of 2 for 20 steps; spread within a mode was at most 0.09 s.
Wan, 2 denoising steps, fixed seed, time from
POST /v1/videosto the last byte of the content:cae69be) against this branch, A B A with five requests each after a warmup, medians; all 18 MP4s had the same md5.DecodingStagenow 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 seeDecodingStagerise while end-to-end latency drops.🤖 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