lingbot-world-v2-mps / tools /vae_zero_fixpoint.py
IsaacLiu's picture
Skip the constant tail of the I2V conditioning encode, and cache the rest
be9e101 verified
Raw History Blame Contribute Delete
8.04 kB
#!/usr/bin/env python3
"""Locate the temporal fixpoint of the VAE encoder on I2V zero padding.
`WanI2V._generate_causal_fast` builds its conditioning tensor as the real first
frame followed by `F - 1` zero frames (`wan/image2video.py:893-901`) and encodes
the whole thing. At 480x832 with `frame_num=121` that is 28 temporal chunks of
which 27 are pure zeros, times 8 spatial tiles: 216 of 224 `forward_down` calls
see nothing but zeros.
Whether that work is *removable* is a separate question, and this script answers
it. The encoder is causal with a rolling `feat_cache` of CACHE_T frames per conv
(`vae2_1.py:555-580`), so latent frames in the zero region still depend on the
real frame through that cache -- but only until the cache stops changing. Past
that point identical (all-zero) input must produce identical output, and every
further latent frame is a copy of its predecessor.
So: find the smallest k0 with `latent[:, k] == latent[:, k0]` exactly for all
k >= k0. If k0 is small, the encode can compute frames 0..k0 and broadcast the
rest, which is bit-exact rather than approximate. If the tail only *approaches*
a constant without reaching one, bit-exactness is off the table and the fix
needs a different justification.
Only the VAE is loaded -- no DiT, no T5 -- so this runs in well under the
footprint of a real generate.
Usage:
python tools/vae_zero_fixpoint.py --frame_num 21 # quick, ~1 min
python tools/vae_zero_fixpoint.py # real config
python tools/vae_zero_fixpoint.py --device cpu --frame_num 13 --size 128*128
"""
import argparse
import os
import sys
import time
import numpy as np
import torch
import torchvision.transforms.functional as TF
from PIL import Image
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from wan.modules.vae2_1 import Wan2_1_VAE # noqa: E402
from wan.utils.device import get_device # noqa: E402
VAE_STRIDE = (4, 8, 8)
PATCH_SIZE = (1, 2, 2)
def parse_args():
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('--ckpt_dir', default='ckpt')
p.add_argument('--vae_checkpoint', default='Wan2.1_VAE.pth')
p.add_argument('--image', default='examples/03/image.jpg')
p.add_argument('--frame_num', type=int, default=121)
p.add_argument('--chunk_size', type=int, default=4)
p.add_argument('--size', default='480*832',
help="'HxW' area budget, as in generate.py --size")
p.add_argument('--tile_size', type=int, default=None,
help='latent px; None = per-backend default, 0 = off')
p.add_argument('--tile_halo', type=int, default=16)
p.add_argument('--device', default=None, help="'mps', 'cpu', 'cuda'")
return p.parse_args()
def main():
args = parse_args()
device = torch.device(args.device) if args.device else get_device()
a, b = args.size.split('*')
max_area = int(a) * int(b)
img = Image.open(args.image).convert('RGB')
img = TF.to_tensor(img).sub_(0.5).div_(0.5)
# Size math verbatim from image2video.py:797-809.
h, w = img.shape[1:]
aspect_ratio = h / w
lat_h = round(
np.sqrt(max_area * aspect_ratio) // VAE_STRIDE[1] //
PATCH_SIZE[1] * PATCH_SIZE[1])
lat_w = round(
np.sqrt(max_area / aspect_ratio) // VAE_STRIDE[2] //
PATCH_SIZE[2] * PATCH_SIZE[2])
h, w = lat_h * VAE_STRIDE[1], lat_w * VAE_STRIDE[2]
lat_f = (args.frame_num - 1) // VAE_STRIDE[0] + 1
lat_f = int(lat_f - (lat_f % args.chunk_size))
F = (lat_f - 1) * 4 + 1
iter_ = 1 + (F - 1) // 4
vae = Wan2_1_VAE(vae_pth=os.path.join(args.ckpt_dir, args.vae_checkpoint),
device=device, tile_size=args.tile_size,
tile_halo=args.tile_halo)
spans = vae._tile_grid(lat_h, lat_w)
n_tiles = 1 if spans is None else len(spans[0]) * len(spans[1])
print(f'device={device} tile_size={vae.tile_size} halo={vae.tile_halo}')
print(f'requested {args.frame_num} -> encoded F={F}, latent '
f'{lat_f}x{lat_h}x{lat_w}, {iter_} temporal chunks, {n_tiles} tiles')
print(f'forward_down calls: {n_tiles * iter_} total, '
f'{n_tiles * (iter_ - 1)} on pure zeros')
# The conditioning tensor, exactly as image2video.py:893-901 builds it.
padded = torch.concat([
torch.nn.functional.interpolate(
img[None].cpu(), size=(h, w), mode='bicubic').transpose(0, 1),
torch.zeros(3, F - 1, h, w)
], dim=1).to(device)
print(f'input {tuple(padded.shape)} '
f'({padded.numel() * 4 / 2**30:.2f} GiB fp32)')
t0 = time.time()
latent = vae.encode([padded])[0]
dt = time.time() - t0
print(f'encode: {dt:.1f} s ({dt / iter_:.2f} s per temporal chunk)\n')
# Per-frame deviation from the final frame. Exact equality is the thing
# being tested, so no tolerance is applied.
last = latent[:, -1]
dev = [(latent[:, k] - last).abs().max().item() for k in range(lat_f)]
prev = [float('nan')] + [
(latent[:, k] - latent[:, k - 1]).abs().max().item()
for k in range(1, lat_f)]
# `dev[lat_f - 1]` is |z[-1] - z[-1]| = 0 by construction, so the search must
# stop before it -- otherwise the last frame alone always "qualifies" and a
# fixpoint is reported unconditionally. Require at least 2 frames in the
# constant region.
k0 = next((k for k in range(lat_f - 1) if all(d == 0.0 for d in dev[k:])),
None)
print(f'{"k":>4} {"max|z[k]-z[k-1]|":>18} {"max|z[k]-z[-1]|":>18}')
rows = range(lat_f) if lat_f <= 40 else \
list(range(12)) + [-1] + list(range(lat_f - 8, lat_f))
for k in rows:
if k == -1:
print(f'{"...":>4}')
continue
print(f'{k:>4} {prev[k]:>18.3e} {dev[k]:>18.3e}')
print()
if k0 is None:
print('VERDICT: no exact fixpoint -- the tail is never bitwise constant.')
else:
skipped = lat_f - (k0 + 1)
print(f'VERDICT: exact fixpoint at k0={k0}, frames {k0}..{lat_f - 1} '
f'bitwise identical -> skip {skipped}/{lat_f}')
# Everything below is computed here rather than transcribed, so the
# conclusion does not depend on the numbers above surviving the trip out.
scale = max(dev)
ulp = float(np.spacing(np.float32(scale)))
tail = [d for d in dev[:-1] if d > 0]
print(f'\nlatent magnitude {scale:.4f}, float32 ULP {ulp:.3e}')
print(f'smallest nonzero dev {min(tail):.3e} = {min(tail) / ulp:.1f} ULP '
f'-> {"rounding noise" if min(tail) / ulp < 8 else "real signal"}')
ratios = [prev[k + 1] / prev[k] for k in range(1, lat_f - 1)
if prev[k] > 0 and prev[k + 1] > 0]
if ratios:
med = float(np.median(ratios))
print(f'delta ratio median {med:.3f} -> {-np.log2(med):.2f} bits lost '
f'per latent frame; {np.log2(scale / ulp):.1f} frames to reach ULP')
# Savings depend on clip length: the transient is a fixed number of frames,
# so the constant tail is whatever is left over.
print('\nsavings if the tail is cut where dev first falls below tol:')
for tol in (ulp * 4, 1e-5, 1e-3, 1e-2):
hit = next((k for k, d in enumerate(dev[:-1]) if 0 < d <= tol), None)
if hit is None:
continue
row = [f'tol={tol:>8.1e} cut k={hit:>2}']
for fn in (121, 361):
lf = (fn - 1) // 4 + 1
lf -= lf % args.chunk_size
row.append(f'frame_num={fn}: {max(0, lf - (hit + 1)):>2}/{lf} '
f'= {100 * max(0, lf - (hit + 1)) / lf:>4.1f}%')
print(' ' + ' '.join(row))
# Redundant encoding of the verdict, as a check on the output path.
digest = ','.join(f'{d:.6e}' for d in dev)
import hashlib
print(f'\ndev-digest sha8={hashlib.sha256(digest.encode()).hexdigest()[:8]} '
f'n={len(dev)} k0={k0} lat_f={lat_f}(0x{lat_f:x})')
if __name__ == '__main__':
main()