Files
tiny-gpt/mm/compare_gen.py
T
liuhuajie 9e29277715 feat(exp): 四个 Arm 的实验编排与基准脚本
同一模型、同一批 5184 张图、同样 100 epoch,只换监督信号:
- Arm C: VLM 重描述(唯一长 caption)
- Arm D: 同 C 数据,模型缩到 13.4M(5.1M 非嵌入)
- Arm E: prompt 压成 4 个共享模板
- Arm F: 颜色 + 车身两级模板

结果:C/D 颜色词被忽略(码一致率 0.75 / 0.60),
E 降到 0.000 且色相 3/4 命中,F 在 20 格交叉积上只剩 1 列稳定。

bench_strata: strata(Qwen3.8)视觉描述的延迟与吞吐基准,1.06 s/img。
compare_gen: 多检查点批量出图对比。pdl.sh: 分片下载辅助。
2026-12-03 10:37:55 +08:00

104 lines
3.4 KiB
Python

"""Compare generation from: random init vs trained checkpoint vs real data.
Settles the question "did it learn anything at all, or is the output the same
as an untrained model?".
"""
import argparse
import io
import os
import tarfile
import torch
from PIL import Image, ImageDraw
from tokenizers import Tokenizer
import generate as G
from model import GPT
PROMPT = "a duck on a pond"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", default="out_v2a/ckpt_iter5100.pt")
ap.add_argument("--tok", default="../data_mm/tokenizer.json")
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=4)
ap.add_argument("--out", default="../data_mm/compare")
args = ap.parse_args()
device = "cuda"
G.IMG_SIDE, G.LATENT, G.N_IMG = 128, 8, 64
tok = Tokenizer.from_file(args.tok)
vq = G.load_vq(args.vq_ckpt, device)
os.makedirs(args.out, exist_ok=True)
ck = torch.load(args.ckpt, map_location=device, weights_only=False)
cfg = ck["cfg"]
# 1) random init, same architecture, never trained
torch.manual_seed(0)
with torch.device(device):
m_rand = GPT(cfg)
m_rand.eval()
# 2) trained checkpoint
m_trained = GPT(cfg).to(device)
m_trained.load_state_dict(ck["model"])
m_trained.eval()
rows = {}
for name, model in (("random init", m_rand), ("trained 2 epoch", m_trained)):
tiles = []
for i in range(args.n):
torch.manual_seed(100 + i)
codes, _ = G.text_to_image(model, tok, PROMPT, device, 0.9, 50)
tiles.append(G.codes_to_pil(vq, codes, device))
rows[name] = tiles
# 3) real training images, same prompt keyword "duck"
real = []
with tarfile.open(args.shard) as tf:
for mem in tf:
if not mem.isfile() or not mem.name.endswith(".txt"):
continue
cap = tf.extractfile(mem).read().decode("utf-8", "ignore").strip()
if "duck" not in cap.lower():
continue
key = os.path.splitext(mem.name)[0]
try:
img_mem = tf.getmember(key + ".jpg")
except KeyError:
continue
im = Image.open(io.BytesIO(tf.extractfile(img_mem).read())).convert("RGB")
real.append(im.resize((G.IMG_SIDE, G.IMG_SIDE), Image.BICUBIC))
if len(real) >= args.n:
break
rows["real cc3m"] = real
S = G.IMG_SIDE
labels = list(rows.keys())
canvas = Image.new("RGB", (S * args.n, (S + 20) * len(labels)), (255, 255, 255))
d = ImageDraw.Draw(canvas)
for r, lab in enumerate(labels):
d.text((4, r * (S + 20) + 3), lab, fill=(30, 30, 30))
for c, im in enumerate(rows[lab]):
canvas.paste(im, (c * S, r * (S + 20) + 20))
p = os.path.join(args.out, "compare.png")
canvas.save(p)
print(f"saved {p} size={canvas.size}")
# quick numeric check: code histogram distance to real data
with torch.no_grad():
for name, model in (("random init", m_rand), ("trained 2 epoch", m_trained)):
torch.manual_seed(7)
codes, _ = G.text_to_image(model, tok, PROMPT, device, 0.9, 50)
u = len(torch.unique(codes))
print(f"{name}: {u} unique codes used in one image (of 16384)")
if __name__ == "__main__":
main()