flowlensing / code /latency.py
hamees's picture
Add FlowLensing models, code and evals
813c1b9 verified
Raw History Blame Contribute Delete
3.77 kB
import os, time, cv2, torch, numpy as np
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from tqdm import tqdm
from model import NanoDiT # your custom NanoDiT
from ema_pytorch import EMA # still here if you want to swap in EMA weights
from torchmetrics.image import FrechetInceptionDistance
from torchvision.models import resnet18
NUM_CLASSES = 3
IMG_SIZE = 64
IMG_CHANNELS = 1
LATENT_DIM = 512
PATCH_SIZE = 2
MODEL_DEPTH = 6
MODEL_HEADS = 8
DEVICE = "cuda:3" if torch.cuda.is_available() else "cpu"
USE_BF16 = False # flip to False if your GPU cries
torch.set_float32_matmul_precision('high') # amp it up
def load_model(checkpoint_path, compile=False, use_bf16=False):
model = NanoDiT(
input_size=IMG_SIZE,
patch_size=PATCH_SIZE,
in_channels=IMG_CHANNELS,
hidden_size=LATENT_DIM,
depth=MODEL_DEPTH,
num_heads=MODEL_HEADS,
num_classes=NUM_CLASSES,
timestep_freq_scale=1000,
).to(DEVICE)
ckpt = torch.load(checkpoint_path, map_location=DEVICE)
model.load_state_dict(ckpt)
if use_bf16:
model = model.to(torch.bfloat16) # stash weights as bf16
if compile:
print("Compiling… hold tight ⏳")
model = torch.compile(model, mode="max-autotune")
model.eval()
return model
@torch.inference_mode()
def generate_image(
model,
target_class,
*,
ode_steps=100,
cfg_scale=2.0,
num_samples=1,
use_bf16=False,
):
"""
Generates `num_samples` images of `target_class` with optional classifier‑free guidance.
Everything inside the autocast context runs in bf16 when `use_bf16` is True.
"""
autocast_context = torch.autocast(
device_type="cuda",
dtype=torch.bfloat16,
enabled=use_bf16 and torch.cuda.is_available()
)
with autocast_context:
dtype = torch.bfloat16 if use_bf16 else torch.float32
z = torch.randn(
(num_samples, IMG_CHANNELS, IMG_SIZE, IMG_SIZE),
device=DEVICE,
dtype=dtype,
)
y = torch.tensor([target_class] * num_samples, device=DEVICE, dtype=torch.long)
using_cfg = cfg_scale >= 1.0
if using_cfg:
null_id = torch.tensor([NUM_CLASSES] * num_samples, device=DEVICE)
y = torch.cat([y, null_id], 0)
dt = (1.0 / ode_steps)
dt = torch.tensor(
[dt] * num_samples, device=DEVICE, dtype=dtype
).view(num_samples, *([1] * (z.ndim - 1)))
# Reverse‑time ODE sampler
for i in range(ode_steps, 0, -1):
z_final = torch.cat([z, z], 0) if using_cfg else z
t = torch.full(
(z_final.size(0),),
i / ode_steps,
device=DEVICE,
dtype=dtype,
)
v_pred = model(z_final, t, y)
if using_cfg:
pred_cond, pred_uncond = v_pred.chunk(2, 0)
v_pred = pred_uncond + cfg_scale * (pred_cond - pred_uncond)
z = (z - dt * v_pred).to(dtype)
images = torch.clamp((z + 1) / 2.0, 0.0, 1.0)
return images.cpu() # back on CPU as float32 for downstream use
if __name__ == "__main__":
model = load_model(
"checkpoints/flowlensing_dit_class_cond.pth",
compile=False,
use_bf16=USE_BF16,
)
times = []
for _ in tqdm(range(105), desc="Sampling"):
start = time.time()
_ = generate_image(model, target_class=0, use_bf16=USE_BF16)
times.append((time.time() - start) * 1000)
# ignore first 5 runs (warm‑up jit)
print(f"Mean latency: {np.mean(times[5:]):.2f} ms (bf16={USE_BF16})")