跳到正文
DEV Community· MartianAcademy·· 38 分鐘前AI 評分73

如何在 1.8 GB VRAM 下運行 25.6 GB BF16 HunyuanVideo-13B,且不使用量化

How I Ran 25.6 GB BF16 HunyuanVideo-13B in 1.8 GB VRAM Without Quantization

AI 導讀

MartianAcademy以逐區塊權重串流,在峯值 1,807.1 MB VRAM 下運行 25.64 GB BF16 HunyuanVideo-13B,輸出與參考結果 bit-exact。

正文

Over the past week I have been testing how far per-block weight streaming can be pushed on large video and image Diffusion Transformers (Wan2.1-14B, full BF16 HunyuanVideo-13B, MiniMax-H3's 36-block ViT3D Video VAE, and Z-Image-Turbo on Apple Unified Memory) without dropping weights to lossy 4-bit quantization.

Below is a breakdown of the exact memory bottlenecks, two subtle PyTorch and MMDiT bugs that silently corrupted outputs during implementation, one popular attention optimization that failed our benchmark gate, and the final measured numbers.

  1. The Hardware Wall: Why Stage Offloading and Native Low-VRAM Modes Still Hit Limits

Even after splitting a diffusion pipeline into three strict sequential stages (Text Encoder, then DiT, then Tiled VAE) and flushing GPU memory between stages, four practical limits remain:

First, full BF16 MMDiT checkpoints exceed 24 GB consumer cards. Full BF16 HunyuanVideo-13B (20 double-stream blocks plus 40 single-stream blocks) is 25.64 GB on disk. Under an enforced 24.0 GiB VRAM limit (RTX 3090 / 4090 class), standard GPU loading crashes immediately with CUDA OutOfMemoryError at 24.48 GiB.

Second, synchronous layer shuttling keeps VRAM near the ceiling and stalls on PCIe transfers. On Wan2.1-T2V-14B FP8 (14.29 GB, 40 blocks, 832x480x17 frames, 12 steps) running on a 14.58 GiB Tesla T4, native ComfyUI lowvram mode peaks at 14,135.9 MB (13.80 GiB) and takes 180.73 seconds (15.06 seconds per step).

Third, 3D and ViT3D Video VAEs run out of memory at Stage 3. MiniMax-H3's 36-block 4.85 GB ViT3D Video VAE decoding 141 frames at 736x416 crashes a 14.5 GiB T4 (exceeding 14,300.8 MB) because all 36 decoder blocks, unused encoder weights, and multi-tile spatial row buffers sit in VRAM together.

Fourth, 4-bit quantization degrades DiT image quality significantly. On a 19.5 GB Z-Image-Turbo BF16 + Qwen 3.4B suite (1024x1024, 8 steps), 4-bit Q4 quantization lowered memory to 4.81 GB, but dropped visual quality to 19.25 dB PSNR (16.22 pixel MAE) compared to full BF16.

  1. Problem 1: Hiding PCIe Latency Without Corrupting Weights (The CUDACachingAllocator Stream Race)

To decouple Peak VRAM from checkpoint size without changing weight precision:

  • Repeating transformer blocks are discovered automatically, pinned once in host RAM using 4 parallel threads, and replaced on the GPU with 0-element placeholder tensors.
  • A dedicated CUDA prefetch stream copies block i+1 from pinned host RAM to GPU asynchronously while the main compute stream executes block i. Once block i finishes, its GPU parameters are evicted back to 0 elements so at most two blocks ever occupy VRAM.

Bug 1 — Silent Weight Corruption During GEMMs:
In early CUDA runs on a 24-block FP16 DiT, outputs randomly diverged from the monolithic reference (max absolute difference of 9.656) without raising any CUDA error.

Root Cause:
Prefetched block weights were allocated on prefetch_stream, read by matrix multiplications on compute_stream, and released in block i's post-forward hook. Because PyTorch's CUDACachingAllocator tracks buffer safety per stream unless explicitly notified, prefetch_stream immediately reused block i's GPU memory buffer to DMA-overwrite block i+2 while compute_stream was still mid-matmul on block i.

Fix and Measured Result:
Calling tensor.record_stream(compute_stream) on every prefetched parameter tensor, paired with a 2-deep torch.cuda.Event backpressure queue so prefetch never runs more than one block ahead of compute, reduced max absolute difference to 0.0 (bit-exact). Peak VRAM on the 24-block DiT dropped from 4,610.0 MB to 322.2 MB (93.0% saved), and 4-step runtime was 1.074 seconds vs 1.024 seconds monolithic (+4.9% total PCIe overhead).

  1. Problem 2: Zero-DMA First-Block Residual Caching and the In-Place MMDiT Trap

Standard First-Block Cache / TeaCache approaches execute block 0 on every step, measure the relative L1 change in the first-block residual delta_0(t) = block_0(x_t) - x_t, and skip FLOPs for blocks 1 through N-1 when accumulated change stays below a threshold.

When blocks 1 through N-1 live in pinned CPU RAM or safetensors mmap, wiring the cache directly into the block streamer gives a much larger win: on a cache hit, the streamer cancels PCIe DMA and NVMe mmap reads for all N-1 skipped blocks.

On Wan2.1-14B FP8 (12 steps on Tesla T4):

  • Native ComfyUI lowvram baseline: 14,135.9 MB Peak VRAM, 180.73 seconds (15.06 s/step).
  • Lossless block streaming (threshold 0.0): 1,808.2 MB Peak VRAM (87.2% less VRAM), 178.83 seconds (1.01x faster), 0.0 bit-exact difference (99.99 dB PSNR).
  • Streamed + First-Block Cache (threshold 0.12): 1,960.5 MB Peak VRAM, 120.39 seconds (1.50x faster, 4 of 12 steps skipped, PCIe traffic reduced from 160.9 GB to 108.6 GB), 42.67 dB PSNR (0.9995 cosine similarity).
  • Streamed + First-Block Cache (threshold 0.22): 1,960.5 MB Peak VRAM, 93.11 seconds (1.94x faster, 6 of 12 steps skipped, 82.4 GB streamed), 35.91 dB PSNR (0.9973 cosine similarity).

Bug 2 — Dual-Stream MMDiT Collapse to 7.94 dB PSNR:
Extending this to dual-stream MMDiTs (FLUX.1 and HunyuanVideo, which run double_blocks returning (img, txt), concatenate txt and img, and then run single_blocks) exposed two architectural traps:

Trap A: HunyuanVideo runs 2 txt_in token-refiner blocks before double_blocks. Probing delta_0 on txt_in.0 fails because pure text refinement does not track the noisy video latent. Leading text-refiner groups have to be skipped so the cache probes double_blocks.0.

Trap B: Even after probing double_blocks.0, our first 25.64 GB BF16 HunyuanVideo-13B run skipped 7 of 12 steps unconditionally and collapsed to 7.94 dB PSNR (0.296 cosine similarity).
Root Cause: ComfyUI's DoubleStreamBlock (img += ... and txt += ...) and SingleStreamBlock (x += ...) mutate their input tensors in-place. Capturing group entry anchors with detach() without clone() shared underlying tensor storage with the mutated outputs, turning both delta_0 and the stored group residuals into exact zeros (0.0).

Fix and Measured Result (25.64 GB BF16 HunyuanVideo-13B under a strict 24.0 GiB RTX 4090 cap, 640x368x17 frames, 12 steps):

  • Stock highvram and native lowvram: Crashed with CUDA OutOfMemoryError at 24,534.5 MB.
  • Lossless streamed cpu_offload (threshold 0.0): 1,807.1 MB Peak VRAM (92.8% less than model size), 12.12 seconds (1.01 s/step), 0.0 bit-exact (99.99 dB PSNR).
  • Streamed + Multi-Group MMDiT Cache (threshold 0.12): 1,861.5 MB Peak VRAM, 10.45 seconds (1.16x faster, 69.4 GB less PCIe DMA), 36.85 dB PSNR (0.9950 cosine similarity).
  • Streamed + Multi-Group MMDiT Cache (threshold 0.18): 1,861.5 MB Peak VRAM, 7.92 seconds (1.53x faster, 115.6 GB less PCIe DMA), 28.05 dB PSNR (0.9616 cosine similarity).
  1. What Failed Our Benchmark Gate: SageAttention v1.0.6 vs PyTorch 2.11 SDPA

We benchmarked PyPI sageattention 1.0.6 (Triton v1) against native PyTorch 2.11+cu128 scaled_dot_product_attention on 49-frame Wan2.1-14B (20,280 tokens per head) on an A100:

  • Native PyTorch 2.11 SDPA: 36.75 seconds (4.59 s/step), 3,863.3 MB (3.77 GiB) Peak VRAM, 99.99 dB PSNR.
  • PyPI sageattention 1.0.6: 39.90 seconds (slower) and 23.95 dB PSNR (lossy).

We rejected sageattention 1.0.6 completely and kept only two 100% lossless (0.0 diff) attention fastpaths:

  1. On pre-Ampere GPUs (below SM80, such as Tesla T4 and RTX 20-series), clamping and casting BF16 Q, K, V to FP16 inside SDPA prevents PyTorch from falling back to unfused O(N^2) FP32 math attention, saving 1.11 GiB of Peak VRAM on Wan2.1.
  2. On non-Flash devices (Apple MPS, pre-Ampere CUDA, or masked attention), slicing long queries along the sequence axis (chunk size 8192) cuts attention workspace memory 4x to 9x with 0.0 max absolute difference.

  3. Apple Silicon Unified Memory (MLX): Hybrid Residency vs Pure MMap vs 4-Bit Q4

On Unified Memory Macs, MLX evaluates computation graphs lazily. Without forcing mx.eval per block and evicting finished block arrays to 0-element placeholders, all 34 Z-Image-Turbo blocks stay live in Metal memory (26,445.0 MB peak). Pure mmap streaming drops Peak Metal memory to 1,601.0 MB, but reading all blocks from SSD on every step takes 75.04 seconds.

Instead of quantizing to 4-bit Q4, keeping the first K pre-fused (QKV + W13) BF16 blocks resident in Metal up to a fixed Unified Memory budget (for 16 GB or 24 GB Macs) and mmap-streaming only the remaining N-K overflow blocks gave a much better speed-quality-memory trade-off on an M4 Max (19.5 GB Z-Image-Turbo BF16 + Qwen 3.4B + VAE at 1024x1024, 8 steps):

  • Monolithic BF16 baseline: 26,445.0 MB Peak Metal, 41.97 s total (36.80 s denoise), reference quality.
  • 3-Stage + 4-bit Q4 quantized: 4,814.7 MB Peak Metal, 69.72 s total (66.89 s denoise), 19.25 dB PSNR (lossy).
  • Pure mmap block_stream (BF16): 1,601.0 MB Peak Metal (93.9% saved), 75.04 s total (71.45 s denoise), lossless BF16.
  • Hybrid stream (6 GB budget, 14 of 32 blocks resident): 6,068.5 MB Peak Metal (77.1% saved), 50.69 s denoise (1.41x faster than pure mmap, 54.05 s total with 1 cached step), 38.00 dB PSNR (+13.1 dB cleaner than 4-bit Q4).
  • Hybrid stream (8 GB budget, 20 of 32 blocks resident): 8,138.8 MB Peak Metal (69.2% saved), 54.60 s total (1.37x faster than pure mmap, 50.4% fewer SSD reads), 38.18 dB PSNR.
  1. Video and Stereo Audio VAE Streaming (MiniMax-H3 Stage 3 on 14.58 GiB T4)

Applying the same block streamer + encoder eviction + single-tile CPU output buffer to MiniMax-H3's 36-block 4.85 GB ViT3D Video VAE (141 frames at 736x416):

  • Stock monolithic Video VAE: Crashed with CUDA OOM above 14,300.8 MB.
  • Streamed cpu_offload (0 GPU / 36 CPU blocks): 469.7 MB Peak VRAM (96.8% saved), 51.10 seconds, 0.0 bit-exact difference.
  • Streamed hybrid_budget 3 GB (21 GPU / 15 CPU blocks): 3,159.1 MB Peak VRAM, 38.37 seconds (1.33x faster), 0.0 bit-exact.
  • Streamed hybrid_budget 6 GB (36 GPU / 0 CPU blocks): 4,822.5 MB Peak VRAM, 32.75 seconds (1.56x faster), 0.0 bit-exact.
  • Overlapped 4D stereo BigVGAN Audio VAE (32 kHz, 188,000 stereo samples with linear crossfade): 259.6 MB Peak VRAM in 1.95 seconds.

Open question for anyone else working on step caching for 8-step distilled Turbo schedules (such as Z-Image-Turbo or FLUX-schnell): have you found a better probe signal than first-block relative L1? On 8-step linear schedules we observed relative L1 jumps of 0.50 to 0.73 on 6 of the 8 steps, meaning only a single middle step (rel_l1 = 0.21) could be skipped safely above 28 dB PSNR, whereas 12-to-30 step non-distilled schedules skip 35% to 50% of steps cleanly above 36 dB.

Open-Source Implementation (MIT License)

Install via PyPI: pip install phobos-stream
Install in ComfyUI: comfy node install comfyui-phobosstream

GitHub logo martianacademy / ComfyUI-PhobosStream

ComfyUI Zero-VRAM Block-Streaming, Video/Audio VAE Streamer & TeaCache/First-Block Cache (Run Wan2.1-14B in 1.77 GiB VRAM & MiniMax-H3 on 8-16GB GPUs & Macs)

PhobosStream Icon ComfyUI-PhobosStream

Comfy Registry PyPI Core Open In Colab ComfyUI License: MIT

ComfyUI-PhobosStream is a self-contained zero-VRAM stage-offloading and hook-based per-block streaming extension for ComfyUI. It enables consumer hardware — including 8GB/16GB/24GB Apple Silicon Macs and 8GB/12GB/16GB NVIDIA/AMD GPUs — to run massive 12B–33B+ image and video Diffusion Transformers (MiniMax-H3, Wan2.1, FLUX.1, HunyuanVideo) without Out-Of-Memory (OOM) crashes.

MiniMax-H3 5.9s Video + 32kHz Stereo Audio generated via ComfyUI + PhobosStream on Tesla T4
Live Output — MiniMax-H3 (5.88s, 141 frames @ 24fps + 32 kHz Stereo Audio) on a Free 12 GiB RAM + Tesla T4
PhobosStream streamed the 36-block 4.85 GB ViT3D Video VAE in just 466.8 MB Peak VRAM (96.8% saved vs >14.56 GiB OOM).


📊 Verified Empirical Benchmarks

A. NVIDIA CUDA GPU — MiniMax-H3 (33B-Class), Wan2.1 (8 GiB Cap) & 3-Tier HYBRID_BUDGET (Tesla T4)

  • MiniMaxAI/MiniMax-H3 (32B Qwen3-VL + 20B 4-Step Turbo + 4.85 GB 36-block ViT3D Video VAE + 32 kHz Stereo Audio) on a Tesla T4 (14.58 GiB VRAM):

    • Isolated PhobosVAEStreamPatcher Ablation (141 frames @ 736×416, torch…

來源:DEV Community · dev.to