"""VQ round-trip check: image -> 256 discrete codes -> reconstruction.""" import argparse import io import os import sys import tarfile import numpy as np import torch from PIL import Image IMG_SIDE = 256 def load_vq(ckpt_path, device): sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "vendor", "llamagen_vq")) from vq_model import VQ_16 model = VQ_16() sd = torch.load(ckpt_path, map_location="cpu", weights_only=False) if isinstance(sd, dict) and "model" in sd: sd = sd["model"] missing, unexpected = model.load_state_dict(sd, strict=False) print(f"load: missing={len(missing)} unexpected={len(unexpected)}") if missing: print(" e.g. missing:", missing[:5]) model.eval().to(device) return model def prep(im): im = im.convert("RGB") w, h = im.size s = IMG_SIDE / min(w, h) im = im.resize((max(IMG_SIDE, int(round(w * s))), max(IMG_SIDE, int(round(h * s)))), Image.BICUBIC) w, h = im.size left, top = (w - IMG_SIDE) // 2, (h - IMG_SIDE) // 2 im = im.crop((left, top, left + IMG_SIDE, top + IMG_SIDE)) arr = np.asarray(im, dtype=np.float32) / 127.5 - 1.0 return im, arr def main(): ap = argparse.ArgumentParser() ap.add_argument("--vq_ckpt", default="../ckpt/vq_ds16_t2i.pt") ap.add_argument("--shard", default="../data_mm/shards/cc3m-0000.tar") ap.add_argument("--n", type=int, default=8) ap.add_argument("--out_dir", default="../data_mm/vq_check") ap.add_argument("--device", default="cuda") args = ap.parse_args() os.makedirs(args.out_dir, exist_ok=True) vq = load_vq(args.vq_ckpt, args.device) blobs = [] with tarfile.open(args.shard) as tf: for m in tf: if m.isfile() and m.name.lower().endswith((".jpg", ".jpeg", ".png")): blobs.append(tf.extractfile(m).read()) if len(blobs) >= args.n: break print(f"pulled {len(blobs)} images from {args.shard}") imgs, arrs = zip(*[prep(Image.open(io.BytesIO(b))) for b in blobs]) x = torch.from_numpy(np.stack(arrs)).permute(0, 3, 1, 2).to(args.device) with torch.no_grad(): quant, _, info = vq.encode(x) codes = info[2].view(len(blobs), 16, 16) rec = vq.decode(quant).clamp(-1, 1) mse = torch.mean((rec - x) ** 2).item() psnr = 10 * np.log10(4.0 / mse) if mse > 0 else float("inf") uniq = len(torch.unique(codes)) print(f"codes shape {tuple(codes.shape)} range [{codes.min().item()}, {codes.max().item()}]") print(f"unique codes used: {uniq} / 16384 ({uniq/16384*100:.1f}%)") print(f"reconstruction MSE {mse:.5f} PSNR {psnr:.2f} dB") def to_pil(t): a = ((t.float().cpu() + 1) * 127.5).clamp(0, 255).byte().permute(1, 2, 0).numpy() return Image.fromarray(a) for i in range(len(blobs)): to_pil(x[i]).save(os.path.join(args.out_dir, f"{i:02d}_orig.png")) to_pil(rec[i]).save(os.path.join(args.out_dir, f"{i:02d}_rec.png")) np.save(os.path.join(args.out_dir, "codes.npy"), codes.cpu().numpy()) print(f"saved to {args.out_dir}/") if __name__ == "__main__": main()