文本 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)。
175 lines
6.5 KiB
Python
175 lines
6.5 KiB
Python
"""Generate images from text, and captions from images.
|
|
|
|
Constrained decoding matters here: while emitting an image the model must only
|
|
be allowed to pick ids inside the image vocab, otherwise it can leak a text
|
|
token into the 16x16 grid and corrupt the layout. The grid is forced to exactly
|
|
256 tokens, so every sample is decodable.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import os
|
|
import sys
|
|
|
|
import numpy as np
|
|
import torch
|
|
import torch.nn.functional as F
|
|
from PIL import Image
|
|
from tokenizers import Tokenizer
|
|
|
|
from model import GPT, MMConfig, VOCAB_SIZE, TEXT_VOCAB, IMAGE_VOCAB, IMAGE_OFFSET
|
|
from model import PAD, BOS, EOS, IMG_S, IMG_E, TXT_S, TXT_E
|
|
|
|
LATENT = 16
|
|
N_IMG = LATENT * LATENT
|
|
IMG_SIDE = 256
|
|
CODE_DIM = 8
|
|
|
|
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
|
|
|
|
m = VQ_16()
|
|
sd = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
|
if isinstance(sd, dict) and "model" in sd:
|
|
sd = sd["model"]
|
|
m.load_state_dict(sd, strict=False)
|
|
return m.eval().to(device)
|
|
|
|
|
|
@torch.no_grad()
|
|
def sample_next(logits, temperature, top_k, allowed=None):
|
|
if allowed is not None:
|
|
mask = torch.full_like(logits, float("-inf"))
|
|
mask[:, allowed[0] : allowed[1]] = logits[:, allowed[0] : allowed[1]]
|
|
logits = mask
|
|
logits = logits / max(temperature, 1e-5)
|
|
if top_k:
|
|
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
|
logits[logits < v[:, [-1]]] = float("-inf")
|
|
probs = F.softmax(logits, dim=-1)
|
|
return torch.multinomial(probs, 1)
|
|
|
|
|
|
@torch.no_grad()
|
|
def text_to_image(model, tok, prompt, device, temperature=1.0, top_k=100):
|
|
ids = [BOS, TXT_S] + [i for i in tok.encode(prompt).ids if i < TEXT_VOCAB] + [TXT_E, IMG_S]
|
|
x = torch.tensor([ids], dtype=torch.long, device=device)
|
|
img_ids = []
|
|
for step in range(N_IMG):
|
|
ctx = x[:, -model.cfg.block_size :]
|
|
logits = model(ctx)["logits"][:, -1, :]
|
|
allowed = (IMAGE_OFFSET, IMAGE_OFFSET + IMAGE_VOCAB)
|
|
nxt = sample_next(logits, temperature, top_k, allowed)
|
|
img_ids.append(int(nxt))
|
|
x = torch.cat([x, nxt], dim=1)
|
|
x = torch.cat([x, torch.tensor([[IMG_E]], device=device)], dim=1)
|
|
codes = torch.tensor([i - IMAGE_OFFSET for i in img_ids], device=device)
|
|
return codes, x
|
|
|
|
|
|
@torch.no_grad()
|
|
def image_to_text(model, tok, vq, pil_img, device, max_new=48, temperature=0.9, top_k=50):
|
|
arr = prep_image(pil_img)
|
|
x_img = torch.from_numpy(arr).unsqueeze(0).permute(0, 3, 1, 2).to(device)
|
|
_, _, info = vq.encode(x_img)
|
|
codes = info[2].view(N_IMG).tolist()
|
|
ids = [BOS, IMG_S] + [c + IMAGE_OFFSET for c in codes] + [IMG_E, TXT_S]
|
|
x = torch.tensor([ids], dtype=torch.long, device=device)
|
|
out_ids = []
|
|
for _ in range(max_new):
|
|
ctx = x[:, -model.cfg.block_size :]
|
|
logits = model(ctx)["logits"][:, -1, :]
|
|
nxt = sample_next(logits, temperature, top_k, (0, TEXT_VOCAB))
|
|
t = int(nxt)
|
|
if t in (TXT_E, EOS):
|
|
break
|
|
out_ids.append(t)
|
|
x = torch.cat([x, nxt], dim=1)
|
|
return tok.decode(out_ids), codes
|
|
|
|
|
|
def prep_image(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))
|
|
return np.asarray(im, dtype=np.float32) / 127.5 - 1.0
|
|
|
|
|
|
@torch.no_grad()
|
|
def codes_to_pil(vq, codes, device):
|
|
flat = codes.view(-1).to(device)
|
|
rec = vq.decode_code(flat, shape=(1, CODE_DIM, LATENT, LATENT), channel_first=True)
|
|
rec = rec.clamp(-1, 1)[0].float().cpu()
|
|
a = ((rec + 1) * 127.5).clamp(0, 255).byte().permute(1, 2, 0).numpy()
|
|
return Image.fromarray(a)
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--ckpt", default="out_mm/ckpt.pt")
|
|
ap.add_argument("--tok", default="../data_mm/tokenizer.json")
|
|
ap.add_argument("--vq_ckpt", default="../ckpt/vq_ds16_t2i.pt")
|
|
ap.add_argument("--mode", choices=["image", "caption"], default="image")
|
|
ap.add_argument("--prompt", default="a duck on a pond")
|
|
ap.add_argument("--image", default=None, help="input image for --mode caption")
|
|
ap.add_argument("--n", type=int, default=4)
|
|
ap.add_argument("--temperature", type=float, default=1.0)
|
|
ap.add_argument("--top_k", type=int, default=100)
|
|
ap.add_argument("--out", default="../data_mm/gen")
|
|
ap.add_argument("--meta", default="../data_mm/meta.json", help="dataset meta, for grid size")
|
|
ap.add_argument("--seed", type=int, default=0)
|
|
args = ap.parse_args()
|
|
|
|
global LATENT, N_IMG, IMG_SIDE
|
|
if os.path.exists(args.meta):
|
|
with open(args.meta) as f:
|
|
meta = json.load(f)
|
|
IMG_SIDE = meta.get("img_side", 256)
|
|
LATENT = meta.get("img_side", 256) // 16
|
|
N_IMG = meta.get("n_img_tokens", LATENT * LATENT)
|
|
print(f"grid {LATENT}x{LATENT} = {N_IMG} image tokens, {IMG_SIDE}px")
|
|
|
|
torch.manual_seed(args.seed)
|
|
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
ck = torch.load(args.ckpt, map_location=device, weights_only=False)
|
|
cfg = ck["cfg"]
|
|
model = GPT(cfg).to(device)
|
|
model.load_state_dict(ck["model"])
|
|
model.eval()
|
|
tok = Tokenizer.from_file(args.tok)
|
|
vq = load_vq(args.vq_ckpt, device)
|
|
os.makedirs(args.out, exist_ok=True)
|
|
|
|
if args.mode == "image":
|
|
tiles = []
|
|
for i in range(args.n):
|
|
codes, _ = text_to_image(model, tok, args.prompt, device, args.temperature, args.top_k)
|
|
im = codes_to_pil(vq, codes, device)
|
|
p = os.path.join(args.out, f"img_{i:02d}.png")
|
|
im.save(p)
|
|
tiles.append(im)
|
|
print(f"saved {p}")
|
|
if len(tiles) > 1:
|
|
cols = min(4, len(tiles))
|
|
rows = (len(tiles) + cols - 1) // cols
|
|
grid = Image.new("RGB", (cols * IMG_SIDE, rows * IMG_SIDE), (255, 255, 255))
|
|
for i, t in enumerate(tiles):
|
|
grid.paste(t, ((i % cols) * IMG_SIDE, (i // cols) * IMG_SIDE))
|
|
gp = os.path.join(args.out, "grid.png")
|
|
grid.save(gp)
|
|
print(f"saved {gp}")
|
|
else:
|
|
if not args.image:
|
|
raise SystemExit("--mode caption needs --image")
|
|
im = Image.open(args.image)
|
|
cap, _ = image_to_text(model, tok, vq, im, device, temperature=args.temperature, top_k=args.top_k)
|
|
print(f"caption: {cap}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|