6 min read

Setting Up Google Colab and Kaggle for Open-Weight Video Generation (With Example Notebooks)

Running open-weight video generation models like Wan 2.1, Wan 2.2, LTX-Video, and CogVideoX on free cloud notebooks is completely practical in 2026—provided you design around 15GB T4 VRAM ceilings, Kaggle's 20GB /kaggle/working disk cap, and ephemeral session resets.

If you treat a free Colab or Kaggle runtime like a local workstation, your first pip install or huggingface-cli download will either OOM the GPU during VAE decoding or fill /kaggle/working before a single frame renders. This guide walks through the exact architecture, environment variables, symlink patterns, and sanitized notebook workflows that keep Wan2GP, ComfyUI, and Diffusers running reliably on free Colab and Kaggle T4 GPUs.

Architecture diagram comparing Google Colab 1x T4 and Kaggle 2x T4 video generation pipelines

1. Colab vs. Kaggle: Hardware & Storage Reality Check

Before choosing a runtime, map your pipeline to what each free tier actually gives you:

Feature Google Colab (Free) Kaggle Notebooks (Free)
GPU 1x NVIDIA T4 (15GB VRAM) 2x NVIDIA T4 (15GB VRAM each, 30GB aggregate)
System RAM ~12.7GB ~30GB
Persistent Disk Google Drive mount (/content/drive) /kaggle/working (20GB hard cap)
Scratch Disk /content (~70GB–100GB ephemeral) /tmp (~70GB+ ephemeral)
Weekly Quota Dynamic (disconnects on idle/compute limits) ~30 hours/week GPU quota, 12h max per session
Best Use Case Interactive WebUI + Drive auto-sync Dual-GPU batch rendering & pre-attached datasets

Two constraints matter most on a 15GB T4:

  1. System RAM on Colab (~12.7GB) is tighter than VRAM when loading large bf16 text encoders (like umt5-xxl). Use FP8 / INT8 / GGUF quantized encoders and optimum-quanto or --lowvram flags.
  2. Kaggle's 2x T4 does not give you a single 30GB unified memory pool—you get cuda:0 (15GB) and cuda:1 (15GB). You either run two parallel render workers (one prompt per GPU) or offload auxiliary encoders onto the second card.

2. Which Video Models Actually Fit on a 15GB T4?

Stick to 480p (832x480) at 49–81 frames with CPU offloading and VAE tiling enabled:

Model Active Size / Quant Target Resolution T4 Viability
Wan 2.1 T2V 1.3B BF16 / FP8 832x480 · 81 frames Fast, native fit on 15GB T4
Wan 2.1 / 2.2 (14B via Wan2GP / GGUF) INT8 / Q4_K_M + CPU offload 832x480 · 20 steps Works via Wan2GP / --lowvram + quanto
FastWan / Turbo LoRAs 4-step distilled 832x480 · 4–8 steps Best iteration speed on T4
LTX-Video BF16 / FP8 768x512 · 65–97 frames Very fast; low memory footprint
CogVideoX-2B / 5B (INT8) torchao / quanto INT8 720x480 · 49 frames 2B is effortless; 5B requires offload

3. Kaggle Setup: Redirect Caches to /tmp & Symlink /kaggle/input

The #1 reason Kaggle video notebooks crash mid-setup is filling /kaggle/working (20GB max). Hugging Face caches, PyTorch inductor kernels, Triton caches, and pip wheels will silently consume that 20GB quota before you render anything.

Kaggle storage layout showing read-only input weights symlinked into /tmp scratch space while keeping /kaggle/working under its 20GB limit

Cell 1: Verify Dual GPUs & Redirect Every Cache to /tmp

Run this as your very first cell before importing torch, diffusers, or installing packages:

import os
import subprocess

# 1. Redirect all caches and temp builds away from /kaggle/working (20GB cap)
CACHE_ENV = {
    "HF_HOME": "/tmp/hf_cache",
    "HUGGINGFACE_HUB_CACHE": "/tmp/hf_cache/hub",
    "TORCH_HOME": "/tmp/torch_cache",
    "TORCHINDUCTOR_CACHE_DIR": "/tmp/inductor_cache",
    "TORCH_EXTENSIONS_DIR": "/tmp/torch_ext",
    "TRITON_CACHE_DIR": "/tmp/triton_cache",
    "PIP_CACHE_DIR": "/tmp/pip_cache",
    "TMPDIR": "/tmp",
}
for key, path in CACHE_ENV.items():
    os.makedirs(path, exist_ok=True)
    os.environ[key] = path

# 2. Check GPU & disk headroom
print(subprocess.check_output(["nvidia-smi", "--query-gpu=index,name,memory.total", "--format=csv,noheader"]).decode())
print(subprocess.check_output(["df", "-h", "/tmp", "/kaggle/working"]).decode())

Cell 2: Symlink Pre-Uploaded Weights + Launch ComfyUI in /tmp

If you upload large .safetensors checkpoints once as a private Kaggle Dataset, they mount read-only under /kaggle/input/<dataset-name>/. Symlink them into /tmp/ComfyUI/models/... instead of copying or re-downloading them every session:

%%bash
set -euo pipefail

# Install aria2 and cloudflared for fast downloads and remote UI access
apt-get -qq update && apt-get -qq install -y aria2 > /dev/null
curl -fsSL -o /usr/local/bin/cloudflared \
  https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64
chmod +x /usr/local/bin/cloudflared

# Clone ComfyUI into /tmp (keeps /kaggle/working clean)
cd /tmp
if [ ! -d "/tmp/ComfyUI" ]; then
  git clone --depth 1 https://github.com/comfyanonymous/ComfyUI.git /tmp/ComfyUI
fi
pip install -q -r /tmp/ComfyUI/requirements.txt

# Symlink any attached Kaggle dataset checkpoints without duplicating disk usage
mkdir -p /tmp/ComfyUI/models/diffusion_models /tmp/ComfyUI/models/text_encoders /tmp/ComfyUI/models/vae /kaggle/working/outputs
find /kaggle/input -type f -name "*.safetensors" | while read -r f; do
  base="$(basename "$f")"
  case "$base" in
    *vae*) ln -sf "$f" "/tmp/ComfyUI/models/vae/$base" ;;
    *t5*|*clip*|*encoder*) ln -sf "$f" "/tmp/ComfyUI/models/text_encoders/$base" ;;
    *) ln -sf "$f" "/tmp/ComfyUI/models/diffusion_models/$base" ;;
  esac
done

Cell 3: Start ComfyUI (--lowvram) Behind an Ephemeral cloudflared Tunnel

import subprocess, time, re

comfy_proc = subprocess.Popen(
    [
        "python", "/tmp/ComfyUI/main.py",
        "--listen", "127.0.0.1",
        "--port", "8188",
        "--lowvram",
        "--output-directory", "/kaggle/working/outputs",
    ],
    stdout=open("/tmp/comfyui.log", "w"),
    stderr=subprocess.STDOUT,
)

tunnel_proc = subprocess.Popen(
    ["cloudflared", "tunnel", "--url", "http://127.0.0.1:8188", "--no-autoupdate"],
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    text=True,
)

for line in iter(tunnel_proc.stdout.readline, ""):
    match = re.search(r"https://[a-z0-9-]+\.trycloudflare\.com", line)
    if match:
        print("ComfyUI Tunnel URL:", match.group(0))
        break

Tip: Point --output-directory directly to /kaggle/working/outputs so only finished .mp4 renders land in persistent storage, while models and caches stay in /tmp.


4. Google Colab Setup: Drive Persistence + Wan2GP Worker

On Google Colab, you only have a single T4 (15GB), so Wan2GP (which includes built-in optimum-quanto INT8/FP8 quantization and aggressive block offloading) is often smoother than raw ComfyUI for 14B-class models, while Google Drive handles persistence across runtime disconnects.

Cell 1: Mount Drive, Verify GPU, and Install Wan2GP

from google.colab import drive
import torch, os

drive.mount("/content/drive")
OUTPUT_DIR = "/content/drive/MyDrive/video-outputs"
os.makedirs(OUTPUT_DIR, exist_ok=True)

assert torch.cuda.is_available(), "Switch Runtime -> Change runtime type -> T4 GPU"
print(f"GPU: {torch.cuda.get_device_name(0)} | VRAM: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")
%%bash
set -euo pipefail
apt-get -qq update && apt-get -qq install -y aria2 ffmpeg > /dev/null
curl -fsSL -o /usr/local/bin/cloudflared \
  https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64
chmod +x /usr/local/bin/cloudflared

cd /content
if [ ! -d "/content/Wan2GP" ]; then
  git clone --depth 1 https://github.com/deepbeepmeep/Wan2GP.git /content/Wan2GP
fi
pip install -q -r /content/Wan2GP/requirements.txt

Cell 2: Launch Wan2GP + cloudflared + Background Drive Sync

Keep renders writing to local NVMe (/content/Wan2GP/outputs) and sync .mp4 files to Google Drive in the background so Drive I/O never stalls inference:

import os, re, shutil, subprocess, threading, time

os.makedirs("/content/Wan2GP/outputs", exist_ok=True)
DRIVE_OUT = "/content/drive/MyDrive/video-outputs"

def sync_outputs():
    seen = set()
    while True:
        for fname in os.listdir("/content/Wan2GP/outputs"):
            if fname.endswith(".mp4") and fname not in seen:
                src = os.path.join("/content/Wan2GP/outputs", fname)
                dst = os.path.join(DRIVE_OUT, fname)
                if os.path.getsize(src) > 0:
                    shutil.copy2(src, dst)
                    seen.add(fname)
                    print(f"Synced to Drive: {fname}")
        time.sleep(10)

threading.Thread(target=sync_outputs, daemon=True).start()

server = subprocess.Popen(
    ["python", "/content/Wan2GP/wgp.py", "--server-name", "127.0.0.1", "--server-port", "7860"],
    stdout=open("/tmp/wan2gp.log", "w"),
    stderr=subprocess.STDOUT,
)

tunnel = subprocess.Popen(
    ["cloudflared", "tunnel", "--url", "http://127.0.0.1:7860", "--no-autoupdate"],
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    text=True,
)

for line in iter(tunnel.stdout.readline, ""):
    m = re.search(r"https://[a-z0-9-]+\.trycloudflare\.com", line)
    if m:
        print("Wan2GP Tunnel URL:", m.group(0))
        break

Recommended T4 starting preset inside Wan2GP:

  • Resolution: 832x480 (16:9) or 480x832 (9:16)
  • Frames: 81 (~5s at 16fps)
  • Steps: 20 (or 4–8 with a distilled Turbo LoRA)
  • Quantization: int8 / quanto enabled with CPU offload

5. Dual-T4 Parallel Batch Rendering in Diffusers (Kaggle)

If you are running batch prompts on Kaggle's 2x T4, don't leave cuda:1 idle. Spawn one worker per GPU using ProcessPoolExecutor with enable_model_cpu_offload() and vae.enable_tiling() so each 15GB T4 renders its own prompt queue in parallel:

import os
import torch
from concurrent.futures import ProcessPoolExecutor
from diffusers import WanPipeline
from diffusers.utils import export_to_video

def render_on_gpu(task):
    gpu_id, prompt, out_path = task
    os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)

    pipe = WanPipeline.from_pretrained(
        "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
        torch_dtype=torch.bfloat16,
    )
    pipe.enable_model_cpu_offload()
    pipe.vae.enable_tiling()

    frames = pipe(
        prompt=prompt,
        height=480,
        width=832,
        num_frames=81,
        num_inference_steps=20,
        guidance_scale=5.0,
    ).frames[0]

    export_to_video(frames, out_path, fps=16)
    return out_path

if __name__ == "__main__":
    os.makedirs("/kaggle/working/outputs", exist_ok=True)
    jobs = [
        (0, "Slow cinematic dolly shot through a rain-slicked neon alley at dusk, 35mm film grain", "/kaggle/working/outputs/shot_01.mp4"),
        (1, "Aerial drone orbit over misty basalt sea cliffs at sunrise, volumetric fog", "/kaggle/working/outputs/shot_02.mp4"),
    ]
    with ProcessPoolExecutor(max_workers=2) as pool:
        for result in pool.map(render_on_gpu, jobs):
            print("Completed:", result)

6. Security & Notebook Hygiene Checklist

Cloud notebooks make it dangerously easy to leak credentials or expose an unauthenticated WebUI. Follow these rules before sharing or committing any .ipynb file:

  1. Never hardcode tokens in cells: Always read HF_TOKEN, webhook URLs, or notification topics (YOUR_NTFY_TOPIC) from Colab Secrets (google.colab.userdata.get("HF_TOKEN")) or Kaggle Secrets (kaggle_secrets.UserSecretsClient().get_secret("HF_TOKEN")).
  2. Treat trycloudflare.com URLs as public endpoints: Quick cloudflared tunnels have no built-in authentication. Anyone with the URL can queue jobs on your GPU or browse your WebUI output folder. Add Gradio --auth user:pass (or --gradio-auth) if you need a login gate, and never paste live tunnel URLs into public logs.
  3. Verify third-party ComfyUI custom nodes: Avoid running unpinned install.py scripts from random repositories inside sessions that have your Google Drive mounted—especially if your Drive contains private keys or personal backups.
  4. Strip cell outputs before git commit: Clear notebook outputs (nbstripout or jupyter nbconvert --clear-output) so accidental token prints, internal paths, or tunnel URLs never enter git history.

Related Reading

Comments

Leave a Comment

Math verification challenge