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

+53
View File
@@ -0,0 +1,53 @@
"""Evaluate validation loss for a list of checkpoints (no training)."""
import argparse
import glob
import os
import numpy as np
import torch
from model import GPT
from train import get_batch_rows
def eval_ckpt(path, data, row_len, device, bs=32, iters=40, mtp=False):
ck = torch.load(path, map_location=device, weights_only=False)
cfg = ck["cfg"]
model = GPT(cfg).to(device)
model.load_state_dict(ck["model"])
model.eval()
total = 0.0
with torch.no_grad():
for _ in range(iters):
xb, yb, mb = get_batch_rows(data, row_len, bs, device, mtp)
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
out = model(xb, yb, mb)
total += out["loss"].item()
return total / iters
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", default="../data_mm/val.bin")
ap.add_argument("--row_len", type=int, default=320)
ap.add_argument("--ckpts", nargs="+", default=None)
ap.add_argument("--glob", default=None)
ap.add_argument("--iters", type=int, default=40)
args = ap.parse_args()
device = "cuda" if torch.cuda.is_available() else "cpu"
raw = np.memmap(args.data, dtype=np.uint16, mode="r")
data = np.asarray(raw).reshape(-1, args.row_len)
print(f"val rows: {data.shape[0]}")
paths = args.ckpts or sorted(glob.glob(args.glob or "out_mm2/ckpt_iter*.pt"))
for p in paths:
if not os.path.exists(p):
print(f"{p}: missing")
continue
loss = eval_ckpt(p, data, args.row_len, device, iters=args.iters)
print(f"{os.path.basename(p):22s} val_loss {loss:.4f} ppl {np.exp(loss):8.1f}")
if __name__ == "__main__":
main()
+174
View File
@@ -0,0 +1,174 @@
"""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()
+280
View File
@@ -0,0 +1,280 @@
"""Minimal native-multimodal GPT.
Design targets a ~63M single-GPU budget (RTX 4080 Super, 32GB).
What is taken from 2026 practice:
- all-softmax attention: sequences are short (<=512), hybrid/recurrent
attention does not pay off at this length
- GQA with 4 KV heads (the sweet spot reported by Mellum 2)
- RMSNorm, SwiGLU, RoPE, QK-norm
- gated residual with N parallel streams
- hashed n-gram embedding injected at a shallow layer
- multi-token prediction head (one extra block, shared lm_head)
Modality handling: text BPE ids and VQ image ids live in one vocabulary,
so a single softmax covers both. That is what "native" means here.
"""
import math
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
TEXT_VOCAB = 16000
IMAGE_VOCAB = 16384
IMAGE_OFFSET = TEXT_VOCAB
PAD, BOS, EOS, IMG_S, IMG_E, TXT_S, TXT_E = range(TEXT_VOCAB + IMAGE_VOCAB, TEXT_VOCAB + IMAGE_VOCAB + 7)
VOCAB_SIZE = TEXT_VOCAB + IMAGE_VOCAB + 7
@dataclass
class MMConfig:
block_size: int = 512
vocab_size: int = VOCAB_SIZE
n_layer: int = 10
n_head: int = 8
n_kv_head: int = 4
n_embd: int = 448
n_stream: int = 4
mlp_ratio: float = 8.0 / 3.0
ngram_vocab: int = 131072
ngram_dim: int = 64
ngram_layer: int = 2
dropout: float = 0.0
bias: bool = False
use_mtp: bool = True
mtp_weight: float = 0.3
rope_base: float = 10000.0
@property
def head_dim(self) -> int:
return self.n_embd // self.n_head
@property
def mlp_hidden(self) -> int:
h = int(self.mlp_ratio * self.n_embd)
return 64 * ((h + 63) // 64)
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
dt = x.dtype
x = x.float()
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return (x.to(dt)) * self.weight
def _rotate_half(x):
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
def build_rope(head_dim: int, seq_len: int, base: float, device, dtype):
inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
t = torch.arange(seq_len, device=device).float()
freqs = torch.outer(t, inv_freq)
emb = torch.cat([freqs, freqs], dim=-1)
return emb.cos().to(dtype), emb.sin().to(dtype)
def apply_rope(x, cos, sin):
# x: (B, H, T, hd) ; cos/sin: (T, hd)
return x * cos + _rotate_half(x) * sin
class Attention(nn.Module):
def __init__(self, cfg: MMConfig):
super().__init__()
self.n_head = cfg.n_head
self.n_kv_head = cfg.n_kv_head
self.head_dim = cfg.head_dim
self.dropout = cfg.dropout
self.q_dim = self.n_head * self.head_dim
self.kv_dim = self.n_kv_head * self.head_dim
self.c_attn = nn.Linear(cfg.n_embd, self.q_dim + 2 * self.kv_dim, bias=cfg.bias)
self.c_proj = nn.Linear(self.q_dim, cfg.n_embd, bias=cfg.bias)
self.q_norm = RMSNorm(self.head_dim)
self.k_norm = RMSNorm(self.head_dim)
def forward(self, x, cos, sin):
B, T, C = x.shape
q, k, v = self.c_attn(x).split([self.q_dim, self.kv_dim, self.kv_dim], dim=2)
q = q.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
k = k.view(B, T, self.n_kv_head, self.head_dim).transpose(1, 2)
v = v.view(B, T, self.n_kv_head, self.head_dim).transpose(1, 2)
q = self.q_norm(q)
k = self.k_norm(k)
q = apply_rope(q, cos, sin)
k = apply_rope(k, cos, sin)
try:
y = F.scaled_dot_product_attention(
q, k, v, is_causal=True, dropout_p=self.dropout if self.training else 0.0,
enable_gqa=(self.n_head != self.n_kv_head),
)
except TypeError:
rep = self.n_head // self.n_kv_head
k = k.repeat_interleave(rep, dim=1)
v = v.repeat_interleave(rep, dim=1)
y = F.scaled_dot_product_attention(
q, k, v, is_causal=True, dropout_p=self.dropout if self.training else 0.0
)
y = y.transpose(1, 2).contiguous().view(B, T, C)
return self.c_proj(y)
class SwiGLU(nn.Module):
def __init__(self, cfg: MMConfig):
super().__init__()
h = cfg.mlp_hidden
self.w1 = nn.Linear(cfg.n_embd, h, bias=cfg.bias)
self.w3 = nn.Linear(cfg.n_embd, h, bias=cfg.bias)
self.w2 = nn.Linear(h, cfg.n_embd, bias=cfg.bias)
def forward(self, x):
return self.w2(F.silu(self.w1(x)) * self.w3(x))
class Block(nn.Module):
def __init__(self, cfg: MMConfig, with_ngram: bool = False):
super().__init__()
self.ln1 = RMSNorm(cfg.n_embd)
self.attn = Attention(cfg)
self.ln2 = RMSNorm(cfg.n_embd)
self.mlp = SwiGLU(cfg)
self.ngram_proj = nn.Linear(cfg.ngram_dim, cfg.n_embd, bias=False) if with_ngram else None
def forward(self, x, cos, sin, ngram=None):
if self.ngram_proj is not None and ngram is not None:
x = x + self.ngram_proj(ngram)
x = x + self.attn(self.ln1(x), cos, sin)
x = x + self.mlp(self.ln2(x))
return x
class GPT(nn.Module):
def __init__(self, cfg: MMConfig):
super().__init__()
self.cfg = cfg
self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.n_embd)
self.drop = nn.Dropout(cfg.dropout)
self.blocks = nn.ModuleList(
[Block(cfg, with_ngram=(i == cfg.ngram_layer)) for i in range(cfg.n_layer)]
)
# gated residual: mix N parallel streams into one input, distribute output back
self.pre_gate = nn.ModuleList(
[nn.Linear(cfg.n_embd, cfg.n_stream, bias=True) for _ in range(cfg.n_layer)]
)
self.post_gate = nn.ModuleList(
[nn.Linear(cfg.n_embd, cfg.n_stream, bias=True) for _ in range(cfg.n_layer)]
)
self.ngram_emb = nn.Embedding(cfg.ngram_vocab, cfg.ngram_dim)
self.ln_f = RMSNorm(cfg.n_embd)
self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False)
self.tok_emb.weight = self.lm_head.weight # weight tying
self.mtp_block = Block(cfg) if cfg.use_mtp else None
self.apply(self._init_weights)
for name, p in self.named_parameters():
if name.endswith("c_proj.weight") or name.endswith("w2.weight"):
nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * cfg.n_layer))
# gates start near a plain residual net: uniform read, gain spread across
# streams so the branches actually differentiate instead of staying copies
for i, m in enumerate(self.pre_gate):
nn.init.zeros_(m.weight)
nn.init.zeros_(m.bias)
for m in self.post_gate:
nn.init.zeros_(m.weight)
with torch.no_grad():
# beta = 2*sigmoid(.) so the gate is bounded in (0,2); start spread
# across streams to break symmetry
m.bias.copy_(torch.linspace(-1.1, 1.1, cfg.n_stream))
cos, sin = build_rope(cfg.head_dim, cfg.block_size, cfg.rope_base, "cpu", torch.float32)
self.register_buffer("rope_cos", cos, persistent=False)
self.register_buffer("rope_sin", sin, persistent=False)
@staticmethod
def _init_weights(m):
if isinstance(m, nn.Linear):
nn.init.normal_(m.weight, mean=0.0, std=0.02)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Embedding):
nn.init.normal_(m.weight, mean=0.0, std=0.02)
def ngram_ids(self, idx):
prev = F.pad(idx[:, :-1], (1, 0), value=0)
return (prev.to(torch.int64) * 1000003 + idx.to(torch.int64)) % self.cfg.ngram_vocab
def num_params(self, non_embedding: bool = False) -> int:
n = sum(p.numel() for p in self.parameters())
if non_embedding:
n -= self.tok_emb.weight.numel()
return n
def forward(self, idx, targets: Optional[torch.Tensor] = None, mtp_targets: Optional[torch.Tensor] = None):
B, T = idx.shape
assert T <= self.cfg.block_size, f"sequence {T} exceeds block_size {self.cfg.block_size}"
cos = self.rope_cos[:T].to(idx.device)
sin = self.rope_sin[:T].to(idx.device)
x = self.drop(self.tok_emb(idx))
streams = x.unsqueeze(0).expand(self.cfg.n_stream, -1, -1, -1).contiguous()
ngram = self.ngram_emb(self.ngram_ids(idx))
for blk, pre, post in zip(self.blocks, self.pre_gate, self.post_gate):
h = streams.mean(0)
alpha = F.softmax(pre(h), dim=-1) # (B,T,N)
x_in = (alpha.permute(2, 0, 1).unsqueeze(-1) * streams).sum(0) # (B,T,C)
y = blk(x_in, cos, sin, ngram)
beta = 2.0 * torch.sigmoid(post(h)) # (B,T,N), bounded in (0,2)
streams = streams + beta.permute(2, 0, 1).unsqueeze(-1) * y.unsqueeze(0)
h = self.ln_f(streams.mean(0))
logits = self.lm_head(h)
out = {"logits": logits}
if targets is not None:
loss = F.cross_entropy(
logits.view(-1, logits.size(-1)), targets.reshape(-1), ignore_index=-100
)
out["loss"] = loss
if self.mtp_block is not None and mtp_targets is not None:
h_mtp = self.mtp_block(h, cos, sin)
logits_mtp = self.lm_head(h_mtp)
loss_mtp = F.cross_entropy(
logits_mtp.view(-1, logits_mtp.size(-1)),
mtp_targets.reshape(-1),
ignore_index=-100,
)
out["loss_mtp"] = loss_mtp
out["loss_total"] = loss + self.cfg.mtp_weight * loss_mtp
return out
@torch.no_grad()
def generate(self, idx, max_new_tokens=64, temperature=1.0, top_k=None):
for _ in range(max_new_tokens):
ctx = idx[:, -self.cfg.block_size :]
logits = self(ctx)["logits"][:, -1, :] / max(temperature, 1e-5)
if top_k is not None:
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
logits[logits < v[:, [-1]]] = -float("inf")
probs = F.softmax(logits, dim=-1)
idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1)
return idx
+105
View File
@@ -0,0 +1,105 @@
"""Muon optimizer (momentum orthogonalized by Newton-Schulz) plus AdamW fallback.
Only 2D hidden weight matrices go through Muon. Embeddings, the tied lm_head,
norm weights and the residual gates go through AdamW.
Scaling matters more than people expect: the Mellum 2 report found the
Megatron default (extra scale 1.0) diverged after ~21B tokens on a dense 7B
model, while the Moonlight setting (0.2) was stable and beat AdamW. Default
here is therefore "moonlight".
"""
import torch
def zeropower_via_newtonschulz5(G: torch.Tensor, steps: int = 5, eps: float = 1e-7) -> torch.Tensor:
a, b, c = 3.4445, -4.7750, 2.0315
X = G.bfloat16()
transposed = X.size(0) > X.size(1)
if transposed:
X = X.T
X = X / (X.norm() + eps)
for _ in range(steps):
A = X @ X.T
B = b * A + c * (A @ A)
X = a * X + B @ X
if transposed:
X = X.T
return X
class Muon(torch.optim.Optimizer):
def __init__(self, params, lr=0.02, momentum=0.95, nesterov=True,
ns_steps=5, scale="keller", weight_decay=0.0):
defaults = dict(lr=lr, momentum=momentum, nesterov=nesterov,
ns_steps=ns_steps, scale=scale, weight_decay=weight_decay)
super().__init__(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = closure() if closure is not None else None
for group in self.param_groups:
lr = group["lr"]
mom = group["momentum"]
for p in group["params"]:
if p.grad is None:
continue
if p.ndim != 2:
raise ValueError("Muon expects 2D parameters only")
g = p.grad
if group["weight_decay"] > 0:
p.mul_(1 - lr * group["weight_decay"])
state = self.state[p]
if "buf" not in state:
state["buf"] = torch.zeros_like(g)
buf = state["buf"]
buf.mul_(mom).add_(g)
if group["nesterov"]:
g = g.add(buf, alpha=mom)
else:
g = buf
u = zeropower_via_newtonschulz5(g, steps=group["ns_steps"]).to(p.dtype)
if group["scale"] == "moonlight":
u = u * (0.2 * max(p.shape[0], p.shape[1]) ** 0.5)
elif group["scale"] == "keller":
u = u * max(1.0, p.shape[0] / p.shape[1]) ** 0.5
elif group["scale"] == "none":
pass
else:
raise ValueError(f"unknown scale mode {group['scale']}")
p.add_(u, alpha=-lr)
return loss
def build_param_groups(model, lr_muon: float, lr_adam: float, weight_decay: float):
"""Split parameters into Muon (2D hidden matrices) and AdamW (everything else)."""
muon_params, adam_params = [], []
seen = set()
def add(module_or_param, target, name=""):
params = module_or_param if isinstance(module_or_param, (list, tuple)) else [module_or_param]
for p in params:
if p is None or id(p) in seen:
continue
seen.add(id(p))
target.append(p)
# everything that must stay on AdamW
add(model.tok_emb.weight, adam_params, "tok_emb")
add(list(model.pre_gate.parameters()) + list(model.post_gate.parameters()), adam_params, "gates")
add(model.ngram_emb.weight, adam_params, "ngram")
for name, p in model.named_parameters():
if p.ndim != 2:
add(p, adam_params, name)
for name, p in model.named_parameters():
if p.ndim == 2 and id(p) not in seen:
add(p, muon_params, name)
return [
dict(params=muon_params, lr=lr_muon, weight_decay=weight_decay, use_muon=True),
dict(params=adam_params, lr=lr_adam, weight_decay=0.0, use_muon=False),
]
+121
View File
@@ -0,0 +1,121 @@
"""Probe what fits and what is fast on this GPU.
Two safety rules learned the hard way:
1. NEVER instantiate a large model on CPU. Build it inside
`with torch.device('cuda')` so parameters land on the GPU from the start.
Building a 2.7B model on CPU needs ~11GB of host RAM, and building it
twice back-to-back hangs a 30GB machine via swap thrash.
2. Count parameters on the `meta` device, which allocates nothing.
Also estimates memory before trying, and skips runs that clearly will not fit.
"""
import gc
import time
import torch
from model import GPT, MMConfig
PEAK_TFLOPS = 168.0 # measured bf16 matmul peak on this card
def make(n_layer, n_embd, n_head, n_kv, n_stream, block, vocab=32391):
return MMConfig(
block_size=block, vocab_size=vocab, n_layer=n_layer, n_embd=n_embd,
n_head=n_head, n_kv_head=n_kv, n_stream=n_stream, use_mtp=False,
)
def count_params(cfg):
with torch.device("meta"):
m = GPT(cfg)
return sum(p.numel() for p in m.parameters())
def estimate_gb(cfg, batch, bytes_per_param=14.0):
"""Rough memory estimate: optimizer state + activations."""
n = count_params(cfg)
state = n * bytes_per_param / 1e9
tokens = batch * cfg.block_size
act = tokens * cfg.n_layer * cfg.n_embd * 12 * 2 * max(1, cfg.n_stream) / 1e9
return state, act
def try_run(cfg, batch, device="cuda", iters=6):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats()
m = opt = x = y = None
try:
with torch.device(device):
m = GPT(cfg)
opt = torch.optim.AdamW(m.parameters(), lr=1e-4)
x = torch.randint(0, cfg.vocab_size, (batch, cfg.block_size), device=device)
y = torch.randint(0, cfg.vocab_size, (batch, cfg.block_size), device=device)
for _ in range(2):
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
loss = m(x, y)["loss"]
loss.backward()
opt.step()
opt.zero_grad(set_to_none=True)
torch.cuda.synchronize()
t = time.time()
for _ in range(iters):
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
loss = m(x, y)["loss"]
loss.backward()
opt.step()
opt.zero_grad(set_to_none=True)
torch.cuda.synchronize()
dt = (time.time() - t) / iters
return dict(ok=True, mem=torch.cuda.max_memory_allocated() / 1e9,
dt=dt, tok_s=batch * cfg.block_size / dt)
except torch.cuda.OutOfMemoryError:
return dict(ok=False)
finally:
del m, opt, x, y
gc.collect()
torch.cuda.empty_cache()
def main():
torch.backends.cuda.matmul.allow_tf32 = True
free_gb = torch.cuda.mem_get_info()[0] / 1e9
print(f"GPU free: {free_gb:.1f} GB, peak measured {PEAK_TFLOPS:.0f} TFLOPS bf16\n")
sizes = [
("124M", make(12, 768, 12, 4, 2, 512)),
("350M", make(24, 1024, 16, 4, 2, 512)),
("760M", make(24, 1536, 16, 4, 1, 512)),
("1.3B", make(24, 2048, 16, 4, 1, 512)),
("2.7B", make(32, 2560, 20, 4, 1, 512)),
]
print(f"{'size':>6} {'params':>9} {'batch':>6} {'mem GB':>8} {'tok/s':>9} "
f"{'TFLOPS':>8} {'MFU':>6} {'chinchilla':>12}")
for name, cfg in sizes:
n = count_params(cfg)
state, act1 = estimate_gb(cfg, 1)
if state > free_gb * 0.75:
print(f"{name:>6} {n/1e6:8.1f}M {'--':>6} {'SKIP':>8} "
f"optimizer state {state:.1f}GB exceeds {free_gb*0.75:.1f}GB budget")
continue
best = None
for b in (64, 32, 16, 8, 4, 2, 1):
if state + act1 * b > free_gb * 0.92:
continue
r = try_run(cfg, b)
if r["ok"]:
best = (b, r)
break
if best is None:
print(f"{name:>6} {n/1e6:8.1f}M {'--':>6} {'OOM':>8}")
continue
b, r = best
tf = 6 * n * r["tok_s"] / 1e12
hrs = (6 * n * 20 * n) / (tf * 1e12) / 3600 if tf > 0 else 0
print(f"{name:>6} {n/1e6:8.1f}M {b:6d} {r['mem']:8.2f} {r['tok_s']:9.0f} {tf:8.1f} "
f"{tf/PEAK_TFLOPS*100:5.1f}% {hrs:9.1f} h")
if __name__ == "__main__":
main()
+52
View File
@@ -0,0 +1,52 @@
"""Sample from a checkpoint (text-only smoke path)."""
import argparse
import pickle
import torch
from model import GPT, MMConfig
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", type=str, default="out/ckpt.pt")
ap.add_argument("--meta", type=str, default=None, help="meta.pkl for char-level decoding")
ap.add_argument("--prompt", type=str, default="\n")
ap.add_argument("--max_new_tokens", type=int, default=300)
ap.add_argument("--temperature", type=float, default=0.8)
ap.add_argument("--top_k", type=int, default=50)
ap.add_argument("--num_samples", type=int, default=3)
ap.add_argument("--seed", type=int, default=1337)
args = ap.parse_args()
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()
stoi = itos = None
if args.meta:
with open(args.meta, "rb") as f:
meta = pickle.load(f)
stoi, itos = meta["stoi"], meta["itos"]
def encode(s):
return [stoi[c] for c in s] if stoi else [1]
def decode(ids):
return "".join(itos[i] for i in ids) if itos else " ".join(map(str, ids))
ids = encode(args.prompt)
x = torch.tensor(ids, dtype=torch.long, device=device).unsqueeze(0)
for i in range(args.num_samples):
out = model.generate(x, args.max_new_tokens, args.temperature, args.top_k)
print(f"--- sample {i+1} ---")
print(decode(out[0].tolist()))
print()
if __name__ == "__main__":
main()
+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()
+268
View File
@@ -0,0 +1,268 @@
"""Training loop for the small native-multimodal GPT.
Data format: a flat uint16 token stream (text BPE ids and VQ image ids share
one vocabulary), so text-only and interleaved image-text corpora use the same
loader.
Usage:
python train.py --data data/shakespeare_char/train.bin --vocab 65 --max_iters 300
"""
import argparse
import math
import os
import time
import numpy as np
import torch
from model import GPT, MMConfig
from muon import Muon, build_param_groups
def parse_args():
p = argparse.ArgumentParser()
p.add_argument("--data", type=str, required=True, help="flat uint16 token file")
p.add_argument("--val_data", type=str, default="",
help="separate held-out file; without it 'val' is sampled from --data")
p.add_argument("--row_len", type=int, default=0, help=">0 means data is (N, row_len) fixed-length documents")
p.add_argument("--out_dir", type=str, default="out")
p.add_argument("--vocab", type=int, default=None, help="override vocab size")
p.add_argument("--block_size", type=int, default=512)
p.add_argument("--n_layer", type=int, default=10)
p.add_argument("--n_head", type=int, default=8)
p.add_argument("--n_kv_head", type=int, default=4)
p.add_argument("--n_embd", type=int, default=448)
p.add_argument("--n_stream", type=int, default=4)
p.add_argument("--ngram_dim", type=int, default=64)
p.add_argument("--ngram_vocab", type=int, default=131072)
p.add_argument("--batch_size", type=int, default=16)
p.add_argument("--grad_accum", type=int, default=4)
p.add_argument("--max_iters", type=int, default=1000)
p.add_argument("--warmup", type=int, default=100)
p.add_argument("--lr_muon", type=float, default=0.01)
p.add_argument("--lr_adam", type=float, default=6e-4)
p.add_argument("--muon_scale", type=str, default="keller", choices=["keller", "moonlight", "none"])
p.add_argument("--weight_decay", type=float, default=0.1)
p.add_argument("--grad_clip", type=float, default=1.0)
p.add_argument("--mtp", type=int, default=1)
p.add_argument("--mtp_weight", type=float, default=0.3)
p.add_argument("--dtype", type=str, default="bfloat16", choices=["bfloat16", "float16", "float32"])
p.add_argument("--log_interval", type=int, default=50)
p.add_argument("--eval_interval", type=int, default=250)
p.add_argument("--eval_iters", type=int, default=20)
p.add_argument("--save_interval", type=int, default=0, help=">0 saves ckpt_iter{N}.pt every N iters")
p.add_argument("--seed", type=int, default=1337)
p.add_argument("--compile", type=int, default=0)
return p.parse_args()
def get_batch_stream(data, block_size, batch_size, device, mtp):
ix = torch.randint(len(data) - block_size - 2, (batch_size,))
x = torch.stack([torch.from_numpy(data[i : i + block_size].astype(np.int64)) for i in ix])
y = torch.stack([torch.from_numpy(data[i + 1 : i + 1 + block_size].astype(np.int64)) for i in ix])
mtp_y = None
if mtp:
mtp_y = torch.stack(
[torch.from_numpy(data[i + 2 : i + 2 + block_size].astype(np.int64)) for i in ix]
)
return _to_device(x, y, mtp_y, device)
def get_batch_rows(rows, row_len, batch_size, device, mtp, pad_id=32384):
ix = torch.randint(rows.shape[0], (batch_size,))
blk = rows[ix].astype(np.int64)
x = torch.from_numpy(blk)
y = torch.empty_like(x)
y[:, :-1] = x[:, 1:]
y[:, -1] = pad_id
mtp_y = None
if mtp:
mtp_y = torch.empty_like(x)
mtp_y[:, :-2] = x[:, 2:]
mtp_y[:, -2:] = pad_id
# positions that are padding must not contribute to the loss
y = y.masked_fill(x == pad_id, -100)
if mtp_y is not None:
mtp_y = mtp_y.masked_fill(x == pad_id, -100)
return _to_device(x, y, mtp_y, device)
def _to_device(x, y, mtp_y, device):
pin = device.startswith("cuda")
x = x.pin_memory().to(device, non_blocking=True) if pin else x.to(device)
y = y.pin_memory().to(device, non_blocking=True) if pin else y.to(device)
if mtp_y is not None:
mtp_y = mtp_y.pin_memory().to(device, non_blocking=True) if pin else mtp_y.to(device)
return x, y, mtp_y
def lr_at(it, args):
if it < args.warmup:
return (it + 1) / max(1, args.warmup)
prog = (it - args.warmup) / max(1, args.max_iters - args.warmup)
return 0.5 * (1.0 + math.cos(math.pi * min(prog, 1.0)))
def main():
args = parse_args()
torch.manual_seed(args.seed)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
device = "cuda" if torch.cuda.is_available() else "cpu"
ptdtype = {"bfloat16": torch.bfloat16, "float16": torch.float16, "float32": torch.float32}[args.dtype]
ctx = torch.amp.autocast(device_type="cuda", dtype=ptdtype) if device == "cuda" else torch.autocast("cpu", enabled=False)
raw = np.memmap(args.data, dtype=np.uint16, mode="r")
if args.row_len > 0:
assert len(raw) % args.row_len == 0, f"{len(raw)} not divisible by row_len {args.row_len}"
data = np.asarray(raw).reshape(-1, args.row_len)
args.block_size = max(args.block_size, args.row_len)
print(f"data: {args.data} rows={data.shape[0]:,} row_len={args.row_len} "
f"tokens={data.size:,}")
def get_batch(_data, _block, bs, dev, mtp):
return get_batch_rows(_data, args.row_len, bs, dev, mtp)
else:
data = raw
print(f"data: {args.data} tokens={len(data):,}")
def get_batch(_data, _block, bs, dev, mtp):
return get_batch_stream(_data, _block, bs, dev, mtp)
# held-out split: without it the "val" number below is just train data again
val_data = None
if args.val_data:
vraw = np.memmap(args.val_data, dtype=np.uint16, mode="r")
if args.row_len > 0:
assert len(vraw) % args.row_len == 0, f"val {len(vraw)} not divisible by row_len {args.row_len}"
val_data = np.asarray(vraw).reshape(-1, args.row_len)
else:
val_data = vraw
print(f"val: {args.val_data} rows={len(val_data):,}")
cfg = MMConfig(
block_size=args.block_size,
n_layer=args.n_layer,
n_head=args.n_head,
n_kv_head=args.n_kv_head,
n_embd=args.n_embd,
n_stream=args.n_stream,
ngram_dim=args.ngram_dim,
ngram_vocab=args.ngram_vocab,
use_mtp=bool(args.mtp),
mtp_weight=args.mtp_weight,
)
if args.vocab is not None:
cfg.vocab_size = args.vocab
model = GPT(cfg).to(device)
total = model.num_params()
non_emb = model.num_params(non_embedding=True)
print(f"params: {total/1e6:.2f}M total, {non_emb/1e6:.2f}M non-embedding")
print(f"cfg: layers={cfg.n_layer} embd={cfg.n_embd} heads={cfg.n_head}/{cfg.n_kv_head} "
f"streams={cfg.n_stream} mlp={cfg.mlp_hidden} block={cfg.block_size}")
if args.compile:
model = torch.compile(model)
groups = build_param_groups(model, args.lr_muon, args.lr_adam, args.weight_decay)
muon_params = [p for p in groups[0]["params"]]
adam_params = groups[1]["params"]
print(f"muon: {len(muon_params)} tensors ({sum(p.numel() for p in muon_params)/1e6:.2f}M params), "
f"adamw: {len(adam_params)} tensors ({sum(p.numel() for p in adam_params)/1e6:.2f}M params)")
opt_muon = Muon(muon_params, lr=args.lr_muon, momentum=0.95, nesterov=True, scale=args.muon_scale,
weight_decay=args.weight_decay)
opt_adam = torch.optim.AdamW(adam_params, lr=args.lr_adam, betas=(0.9, 0.95), weight_decay=0.0)
# NOTE: args.block_size gets bumped to max(block_size, row_len), so it is NOT
# the real sequence length in row mode. Using it here inflated tok/s by
# block_size/row_len (4x for row_len=128).
seq_len = args.row_len if args.row_len > 0 else args.block_size
tokens_per_iter = args.batch_size * seq_len * args.grad_accum
print(f"tokens/iter: {tokens_per_iter:,}")
os.makedirs(args.out_dir, exist_ok=True)
t0 = time.time()
last_log = t0
running = None
model.train()
for it in range(args.max_iters + 1):
frac = lr_at(it, args)
for g in opt_muon.param_groups:
g["lr"] = args.lr_muon * frac
for g in opt_adam.param_groups:
g["lr"] = args.lr_adam * frac
if it % args.eval_interval == 0 or it == args.max_iters:
model.eval()
with torch.no_grad():
losses = {"train": 0.0, "val": 0.0}
for split in ("train", "val"):
acc = 0.0
src = data if (split == "train" or val_data is None) else val_data
for _ in range(args.eval_iters):
xb, yb, mb = get_batch(src, args.block_size, args.batch_size, device, bool(args.mtp))
with ctx:
out = model(xb, yb, mb)
acc += out["loss_total" if "loss_total" in out else "loss"].item()
losses[split] = acc / args.eval_iters
model.train()
print(f"eval {it:5d}: train {losses['train']:.4f} val {losses['val']:.4f}")
if it == args.max_iters:
break
opt_muon.zero_grad(set_to_none=True)
opt_adam.zero_grad(set_to_none=True)
for micro in range(args.grad_accum):
xb, yb, mb = get_batch(data, args.block_size, args.batch_size, device, bool(args.mtp))
with ctx:
out = model(xb, yb, mb)
loss = out.get("loss_total", out["loss"])
loss = loss / args.grad_accum
loss.backward()
running = loss.item() * args.grad_accum if running is None else 0.9 * running + 0.1 * loss.item() * args.grad_accum
if args.grad_clip > 0:
gnorm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
last_gnorm = float(gnorm)
else:
last_gnorm = float(
sum((p.grad.norm() ** 2).item() for p in model.parameters() if p.grad is not None) ** 0.5
)
if not math.isfinite(last_gnorm) or not math.isfinite(running):
print(f"!! non-finite at iter {it}: loss={running} grad_norm={last_gnorm} -> stop")
break
opt_muon.step()
opt_adam.step()
if it % args.log_interval == 0 and it > 0:
now = time.time()
dt = now - last_log
tok_s = args.log_interval * tokens_per_iter / dt
mem = torch.cuda.max_memory_allocated() / 1e9 if device == "cuda" else 0.0
print(f"iter {it:5d}: loss {running:.4f} gnorm {last_gnorm:6.3f} {tok_s/1000:7.1f}k tok/s "
f"peak_mem {mem:5.2f}GB elapsed {now-t0:6.1f}s")
last_log = now
if args.save_interval > 0 and it > 0 and it % args.save_interval == 0:
p = os.path.join(args.out_dir, f"ckpt_iter{it}.pt")
raw_model = model._orig_mod if hasattr(model, "_orig_mod") else model
torch.save({"model": raw_model.state_dict(), "cfg": cfg, "args": vars(args)}, p)
print(f" saved {p}")
if device == "cuda":
print(f"peak GPU mem: {torch.cuda.max_memory_allocated()/1e9:.2f} GB")
print(f"total time: {time.time()-t0:.1f}s")
raw_model = model._orig_mod if hasattr(model, "_orig_mod") else model
torch.save({"model": raw_model.state_dict(), "cfg": cfg, "args": vars(args)}, os.path.join(args.out_dir, "ckpt.pt"))
print(f"saved {os.path.join(args.out_dir, 'ckpt.pt')}")
if __name__ == "__main__":
main()