Splitting CPU and GPU Stages in a Generative Video Pipeline
Why keeping video decode, model forward passes, and FFmpeg muxing in one GPU worker starves expensive cards, and how bounded DAG stages recover utilization without blowing up VRAM.
The first version of almost every generative video service looks the same: one Python worker running on a GPU machine pulls a job, downloads the source clip, decodes frames with FFmpeg, aligns faces, runs two or three PyTorch models back to back, encodes the output MP4, and uploads it to object storage.
It is easy to ship, and within days of real traffic it hits a counterintuitive bottleneck: queue depth keeps climbing while GPU utilization hovers around 25–35%.
Where the GPU Time Actually Goes
When you profile a single video generation request end to end, the model forward pass is rarely the whole story. On a 15-second 1080p clip, the wall-clock breakdown often looks closer to this:
| download | ffmpeg decode + crop | model A | model B | post + blend | ffmpeg encode + upload |
|---CPU----|---------CPU----------|----GPU----|----GPU----|-----CPU------|----------CPU-----------|If one process holds the GPU slot across the entire timeline, the card sits idle during network I/O, CPU-bound image warping, and H.264/H.265 encoding. You end up paying GPU-hour prices for FFmpeg.
Trying to mask the idle time by running four copies of the monolithic worker on the same card usually makes things worse: all four load duplicate model weights into VRAM, fight over CPU cores during encoding, and OOM the moment two longer clips land on the same worker simultaneously.
Decoupling Stages into an Explicit DAG
The clean fix is to treat video generation as a DAG of heterogeneous stages rather than a single RPC call, separating control-plane orchestration (typically Go) from stateless compute pools (CPU nodes vs. GPU nodes).
┌──> [audio feature (CPU)] ──┐
[download & probe] ┤ ├──> [model forward (GPU)] -> [blend & mux (CPU)] -> [upload]
└──> [frame align (CPU)] ────┘Once stages are decoupled:
- CPU-heavy work scales on cheap CPU pods. FFmpeg decoding, landmark alignment, color blending, and final muxing no longer block a GPU card.
- GPU workers only see ready-to-compute tensors or tightly packed frame chunks. One GPU worker loads weights once and keeps CUDA busy with small batches or overlapped streams.
- Independent branches run in parallel. Audio feature extraction and visual preprocessing no longer serialize each other.
Avoid Passing Raw Frames Through the Orchestrator
The fastest way to ruin a split pipeline is routing uncompressed frame arrays through your Go orchestrator or Redis. Keep the orchestrator strictly on the control plane (passing lightweight URIs, frame ranges, and checksums), and move bulk payloads via shared local NVMe (within a node) or high-throughput object storage / shared POSIX cache (across nodes).
type StageTask struct {
JobID string `json:"job_id"`
NodeID string `json:"node_id"`
Pool string `json:"pool"` // "cpu-media" | "gpu-infer"
InputRefs map[string]string `json:"input_refs"`
OutputPrefix string `json:"output_prefix"`
Attempt int `json:"attempt"`
DeadlineAt int64 `json:"deadline_at"`
}Backpressure and Bounded Queues Between Stages
If CPU preprocessing runs 5x faster than GPU inference, an unbounded queue between them turns into a disk and memory bomb: thousands of decoded frame directories pile up waiting for the GPU, filling scratch storage and expiring before inference ever starts.
Every edge in the DAG needs a bounded handoff buffer and explicit backpressure:
- Bound in-flight intermediate artifacts per GPU pool (for example, keep at most
2 × gpu_workersjobs prefetched and decoded). - Drop stale work early. Check
DeadlineAtbefore starting a GPU stage. Running an expensive 20-second forward pass for a request whose caller already timed out burns GPU capacity twice — once on the dead job and again by delaying the live job behind it. - Isolate fast vs. slow queues. A 5-minute HD batch render should never sit ahead of a 6-second interactive preview in the same FIFO queue.
Practical GPU Worker Habits That Prevent 3 AM OOMs
Even after moving CPU work off the GPU pool, Python inference workers have their own failure patterns:
import torch
class InferenceSlot:
def __init__(self, model, max_frames_per_chunk: int = 64):
self.model = model
self.max_frames = max_frames_per_chunk
@torch.inference_mode()
def run_chunks(self, frames: torch.Tensor) -> list[torch.Tensor]:
outputs: list[torch.Tensor] = []
for start in range(0, frames.shape[0], self.max_frames):
chunk = frames[start : start + self.max_frames].to("cuda", non_blocking=True)
out = self.model(chunk)
outputs.append(out.to("cpu", non_blocking=True))
del chunk, out
torch.cuda.synchronize()
return outputsThree habits eliminated most of our production GPU surprises:
- Chunk by a hard frame/pixel budget, never by "one whole video." User uploads vary wildly in duration and resolution. Bounding peak activation memory per chunk makes VRAM usage predictable regardless of clip length.
- Pre-allocate or warm up with the worst-case shape at startup. Letting PyTorch's caching allocator fragment VRAM across arbitrary resolutions eventually triggers false OOMs hours into a deployment. Bucket incoming resolutions or warm up fixed shapes during container readiness probes.
- Separate process supervision for FFmpeg. Any subprocess invoked in a CPU media worker must run under a strict wall-clock timeout and process-group kill (
killpg); hung FFmpeg processes are one of the most common causes of silent worker leaks.
Trade-offs Worth Acknowledging
Splitting a monolith into a heterogeneous DAG is not free:
| Dimension | Monolithic GPU Worker | Heterogeneous DAG |
|---|---|---|
| Cold-start & local dev | Single process, trivial to run | Needs queue + artifact store + orchestrator |
| End-to-end latency (low load) | Slightly lower (zero serialization hops) | Extra hop overhead between stages |
| GPU utilization under load | Often 20–40% | Consistently 70–85%+ |
| Cost per generated minute | High (GPU pays for CPU/I/O) | Substantially lower; pools scale independently |
| Partial retry on failure | Redoes everything from scratch | Retries only the failed stage |
If your service handles a handful of jobs an hour on one card, stay monolithic and keep life simple. The moment GPU spend starts dominating your infrastructure bill — or different models in the same pipeline need different GPU SKUs — separating CPU preprocessing, GPU inference, and DAG orchestration pays back immediately.