feat(core): 原生多模态 GPT 与训练主干

文本 BPE 与图像 VQ 码共用 32391 词表、单 softmax;GQA 8/4、RoPE、QK-norm、
SwiGLU、4 路门控残差、bigram 表注入第 2 层、输出与嵌入共享权重;
Muon(矩阵)+ AdamW(嵌入/归一化)分组优化。

train.py 本次修两处:
- 新增 --val_data:此前 row 模式下 val 仍从 train.bin 采样,
  train/val gap≈0 是假象,所有“完美泛化”的结论都不可信
- 新增 --ngram_vocab / --ngram_dim:默认 131072x64 的 8.39M 参数
  会占满小模型预算,缩模型实验必须能调

vendor/llamagen_vq 为 VQ 编解码依赖(第三方,56K)。
This commit is contained in:
liuhuajie committed 2026-12-03 10:37:55 +08:00
1 parent da8e9e95c8
commit 003c78f669
11 files changed
+1884

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
"""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()