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()
+152
View File
@@ -0,0 +1,152 @@
# Modified from:
# taming-transformers: https://github.com/CompVis/taming-transformers
import functools
import torch
import torch.nn as nn
class NLayerDiscriminator(nn.Module):
"""Defines a PatchGAN discriminator as in Pix2Pix
--> see https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
"""
def __init__(self, input_nc=3, ndf=64, n_layers=3, use_actnorm=False):
"""Construct a PatchGAN discriminator
Parameters:
input_nc (int) -- the number of channels in input images
ndf (int) -- the number of filters in the last conv layer
n_layers (int) -- the number of conv layers in the discriminator
norm_layer -- normalization layer
"""
super(NLayerDiscriminator, self).__init__()
if not use_actnorm:
norm_layer = nn.BatchNorm2d
else:
norm_layer = ActNorm
if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
use_bias = norm_layer.func != nn.BatchNorm2d
else:
use_bias = norm_layer != nn.BatchNorm2d
kw = 4
padw = 1
sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
nf_mult = 1
nf_mult_prev = 1
for n in range(1, n_layers): # gradually increase the number of filters
nf_mult_prev = nf_mult
nf_mult = min(2 ** n, 8)
sequence += [
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
norm_layer(ndf * nf_mult),
nn.LeakyReLU(0.2, True)
]
nf_mult_prev = nf_mult
nf_mult = min(2 ** n_layers, 8)
sequence += [
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
norm_layer(ndf * nf_mult),
nn.LeakyReLU(0.2, True)
]
sequence += [
nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map
self.main = nn.Sequential(*sequence)
self.apply(self._init_weights)
def _init_weights(self, module):
if isinstance(module, nn.Conv2d):
nn.init.normal_(module.weight.data, 0.0, 0.02)
elif isinstance(module, nn.BatchNorm2d):
nn.init.normal_(module.weight.data, 1.0, 0.02)
nn.init.constant_(module.bias.data, 0)
def forward(self, input):
"""Standard forward."""
return self.main(input)
class ActNorm(nn.Module):
def __init__(self, num_features, logdet=False, affine=True,
allow_reverse_init=False):
assert affine
super().__init__()
self.logdet = logdet
self.loc = nn.Parameter(torch.zeros(1, num_features, 1, 1))
self.scale = nn.Parameter(torch.ones(1, num_features, 1, 1))
self.allow_reverse_init = allow_reverse_init
self.register_buffer('initialized', torch.tensor(0, dtype=torch.uint8))
def initialize(self, input):
with torch.no_grad():
flatten = input.permute(1, 0, 2, 3).contiguous().view(input.shape[1], -1)
mean = (
flatten.mean(1)
.unsqueeze(1)
.unsqueeze(2)
.unsqueeze(3)
.permute(1, 0, 2, 3)
)
std = (
flatten.std(1)
.unsqueeze(1)
.unsqueeze(2)
.unsqueeze(3)
.permute(1, 0, 2, 3)
)
self.loc.data.copy_(-mean)
self.scale.data.copy_(1 / (std + 1e-6))
def forward(self, input, reverse=False):
if reverse:
return self.reverse(input)
if len(input.shape) == 2:
input = input[:,:,None,None]
squeeze = True
else:
squeeze = False
_, _, height, width = input.shape
if self.training and self.initialized.item() == 0:
self.initialize(input)
self.initialized.fill_(1)
h = self.scale * (input + self.loc)
if squeeze:
h = h.squeeze(-1).squeeze(-1)
if self.logdet:
log_abs = torch.log(torch.abs(self.scale))
logdet = height*width*torch.sum(log_abs)
logdet = logdet * torch.ones(input.shape[0]).to(input)
return h, logdet
return h
def reverse(self, output):
if self.training and self.initialized.item() == 0:
if not self.allow_reverse_init:
raise RuntimeError(
"Initializing ActNorm in reverse direction is "
"disabled by default. Use allow_reverse_init=True to enable."
)
else:
self.initialize(output)
self.initialized.fill_(1)
if len(output.shape) == 2:
output = output[:,:,None,None]
squeeze = True
else:
squeeze = False
h = output / self.scale - self.loc
if squeeze:
h = h.squeeze(-1).squeeze(-1)
return h
+164
View File
@@ -0,0 +1,164 @@
"""Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models"""
import os, hashlib
import requests
from tqdm import tqdm
import torch
import torch.nn as nn
from torchvision import models
from collections import namedtuple
URL_MAP = {
"vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1"
}
CKPT_MAP = {
"vgg_lpips": "vgg.pth"
}
MD5_MAP = {
"vgg_lpips": "d507d7349b931f0638a25a48a722f98a"
}
def download(url, local_path, chunk_size=1024):
os.makedirs(os.path.split(local_path)[0], exist_ok=True)
with requests.get(url, stream=True) as r:
total_size = int(r.headers.get("content-length", 0))
with tqdm(total=total_size, unit="B", unit_scale=True) as pbar:
with open(local_path, "wb") as f:
for data in r.iter_content(chunk_size=chunk_size):
if data:
f.write(data)
pbar.update(chunk_size)
def md5_hash(path):
with open(path, "rb") as f:
content = f.read()
return hashlib.md5(content).hexdigest()
def get_ckpt_path(name, root, check=False):
assert name in URL_MAP
path = os.path.join(root, CKPT_MAP[name])
if not os.path.exists(path) or (check and not md5_hash(path) == MD5_MAP[name]):
print("Downloading {} model from {} to {}".format(name, URL_MAP[name], path))
download(URL_MAP[name], path)
md5 = md5_hash(path)
assert md5 == MD5_MAP[name], md5
return path
class LPIPS(nn.Module):
# Learned perceptual metric
def __init__(self, use_dropout=True):
super().__init__()
self.scaling_layer = ScalingLayer()
self.chns = [64, 128, 256, 512, 512] # vg16 features
self.net = vgg16(pretrained=True, requires_grad=False)
self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout)
self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout)
self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout)
self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout)
self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout)
self.load_from_pretrained()
for param in self.parameters():
param.requires_grad = False
def load_from_pretrained(self, name="vgg_lpips"):
ckpt = get_ckpt_path(name, os.path.join(os.path.dirname(os.path.abspath(__file__)), "cache"))
self.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False)
print("loaded pretrained LPIPS loss from {}".format(ckpt))
@classmethod
def from_pretrained(cls, name="vgg_lpips"):
if name != "vgg_lpips":
raise NotImplementedError
model = cls()
ckpt = get_ckpt_path(name, os.path.join(os.path.dirname(os.path.abspath(__file__)), "cache"))
model.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False)
return model
def forward(self, input, target):
in0_input, in1_input = (self.scaling_layer(input), self.scaling_layer(target))
outs0, outs1 = self.net(in0_input), self.net(in1_input)
feats0, feats1, diffs = {}, {}, {}
lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4]
for kk in range(len(self.chns)):
feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk])
diffs[kk] = (feats0[kk] - feats1[kk]) ** 2
res = [spatial_average(lins[kk].model(diffs[kk]), keepdim=True) for kk in range(len(self.chns))]
val = res[0]
for l in range(1, len(self.chns)):
val += res[l]
return val
class ScalingLayer(nn.Module):
def __init__(self):
super(ScalingLayer, self).__init__()
self.register_buffer('shift', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])
self.register_buffer('scale', torch.Tensor([.458, .448, .450])[None, :, None, None])
def forward(self, inp):
return (inp - self.shift) / self.scale
class NetLinLayer(nn.Module):
""" A single linear layer which does a 1x1 conv """
def __init__(self, chn_in, chn_out=1, use_dropout=False):
super(NetLinLayer, self).__init__()
layers = [nn.Dropout(), ] if (use_dropout) else []
layers += [nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False), ]
self.model = nn.Sequential(*layers)
class vgg16(torch.nn.Module):
def __init__(self, requires_grad=False, pretrained=True):
super(vgg16, self).__init__()
vgg_pretrained_features = models.vgg16(pretrained=pretrained).features
self.slice1 = torch.nn.Sequential()
self.slice2 = torch.nn.Sequential()
self.slice3 = torch.nn.Sequential()
self.slice4 = torch.nn.Sequential()
self.slice5 = torch.nn.Sequential()
self.N_slices = 5
for x in range(4):
self.slice1.add_module(str(x), vgg_pretrained_features[x])
for x in range(4, 9):
self.slice2.add_module(str(x), vgg_pretrained_features[x])
for x in range(9, 16):
self.slice3.add_module(str(x), vgg_pretrained_features[x])
for x in range(16, 23):
self.slice4.add_module(str(x), vgg_pretrained_features[x])
for x in range(23, 30):
self.slice5.add_module(str(x), vgg_pretrained_features[x])
if not requires_grad:
for param in self.parameters():
param.requires_grad = False
def forward(self, X):
h = self.slice1(X)
h_relu1_2 = h
h = self.slice2(h)
h_relu2_2 = h
h = self.slice3(h)
h_relu3_3 = h
h = self.slice4(h)
h_relu4_3 = h
h = self.slice5(h)
h_relu5_3 = h
vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'])
out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3)
return out
def normalize_tensor(x,eps=1e-10):
norm_factor = torch.sqrt(torch.sum(x**2,dim=1,keepdim=True))
return x/(norm_factor+eps)
def spatial_average(x, keepdim=True):
return x.mean([2,3],keepdim=keepdim)
+424
View File
@@ -0,0 +1,424 @@
# Modified from:
# taming-transformers: https://github.com/CompVis/taming-transformers
# maskgit: https://github.com/google-research/maskgit
from dataclasses import dataclass, field
from typing import List
import torch
import torch.nn as nn
import torch.nn.functional as F
@dataclass
class ModelArgs:
codebook_size: int = 16384
codebook_embed_dim: int = 8
codebook_l2_norm: bool = True
codebook_show_usage: bool = True
commit_loss_beta: float = 0.25
entropy_loss_ratio: float = 0.0
encoder_ch_mult: List[int] = field(default_factory=lambda: [1, 1, 2, 2, 4])
decoder_ch_mult: List[int] = field(default_factory=lambda: [1, 1, 2, 2, 4])
z_channels: int = 256
dropout_p: float = 0.0
class VQModel(nn.Module):
def __init__(self, config: ModelArgs):
super().__init__()
self.config = config
self.encoder = Encoder(ch_mult=config.encoder_ch_mult, z_channels=config.z_channels, dropout=config.dropout_p)
self.decoder = Decoder(ch_mult=config.decoder_ch_mult, z_channels=config.z_channels, dropout=config.dropout_p)
self.quantize = VectorQuantizer(config.codebook_size, config.codebook_embed_dim,
config.commit_loss_beta, config.entropy_loss_ratio,
config.codebook_l2_norm, config.codebook_show_usage)
self.quant_conv = nn.Conv2d(config.z_channels, config.codebook_embed_dim, 1)
self.post_quant_conv = nn.Conv2d(config.codebook_embed_dim, config.z_channels, 1)
def encode(self, x):
h = self.encoder(x)
h = self.quant_conv(h)
quant, emb_loss, info = self.quantize(h)
return quant, emb_loss, info
def decode(self, quant):
quant = self.post_quant_conv(quant)
dec = self.decoder(quant)
return dec
def decode_code(self, code_b, shape=None, channel_first=True):
quant_b = self.quantize.get_codebook_entry(code_b, shape, channel_first)
dec = self.decode(quant_b)
return dec
def forward(self, input):
quant, diff, _ = self.encode(input)
dec = self.decode(quant)
return dec, diff
class Encoder(nn.Module):
def __init__(self, in_channels=3, ch=128, ch_mult=(1,1,2,2,4), num_res_blocks=2,
norm_type='group', dropout=0.0, resamp_with_conv=True, z_channels=256):
super().__init__()
self.num_resolutions = len(ch_mult)
self.num_res_blocks = num_res_blocks
self.conv_in = nn.Conv2d(in_channels, ch, kernel_size=3, stride=1, padding=1)
# downsampling
in_ch_mult = (1,) + tuple(ch_mult)
self.conv_blocks = nn.ModuleList()
for i_level in range(self.num_resolutions):
conv_block = nn.Module()
# res & attn
res_block = nn.ModuleList()
attn_block = nn.ModuleList()
block_in = ch*in_ch_mult[i_level]
block_out = ch*ch_mult[i_level]
for _ in range(self.num_res_blocks):
res_block.append(ResnetBlock(block_in, block_out, dropout=dropout, norm_type=norm_type))
block_in = block_out
if i_level == self.num_resolutions - 1:
attn_block.append(AttnBlock(block_in, norm_type))
conv_block.res = res_block
conv_block.attn = attn_block
# downsample
if i_level != self.num_resolutions-1:
conv_block.downsample = Downsample(block_in, resamp_with_conv)
self.conv_blocks.append(conv_block)
# middle
self.mid = nn.ModuleList()
self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type))
self.mid.append(AttnBlock(block_in, norm_type=norm_type))
self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type))
# end
self.norm_out = Normalize(block_in, norm_type)
self.conv_out = nn.Conv2d(block_in, z_channels, kernel_size=3, stride=1, padding=1)
def forward(self, x):
h = self.conv_in(x)
# downsampling
for i_level, block in enumerate(self.conv_blocks):
for i_block in range(self.num_res_blocks):
h = block.res[i_block](h)
if len(block.attn) > 0:
h = block.attn[i_block](h)
if i_level != self.num_resolutions - 1:
h = block.downsample(h)
# middle
for mid_block in self.mid:
h = mid_block(h)
# end
h = self.norm_out(h)
h = nonlinearity(h)
h = self.conv_out(h)
return h
class Decoder(nn.Module):
def __init__(self, z_channels=256, ch=128, ch_mult=(1,1,2,2,4), num_res_blocks=2, norm_type="group",
dropout=0.0, resamp_with_conv=True, out_channels=3):
super().__init__()
self.num_resolutions = len(ch_mult)
self.num_res_blocks = num_res_blocks
block_in = ch*ch_mult[self.num_resolutions-1]
# z to block_in
self.conv_in = nn.Conv2d(z_channels, block_in, kernel_size=3, stride=1, padding=1)
# middle
self.mid = nn.ModuleList()
self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type))
self.mid.append(AttnBlock(block_in, norm_type=norm_type))
self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type))
# upsampling
self.conv_blocks = nn.ModuleList()
for i_level in reversed(range(self.num_resolutions)):
conv_block = nn.Module()
# res & attn
res_block = nn.ModuleList()
attn_block = nn.ModuleList()
block_out = ch*ch_mult[i_level]
for _ in range(self.num_res_blocks + 1):
res_block.append(ResnetBlock(block_in, block_out, dropout=dropout, norm_type=norm_type))
block_in = block_out
if i_level == self.num_resolutions - 1:
attn_block.append(AttnBlock(block_in, norm_type))
conv_block.res = res_block
conv_block.attn = attn_block
# downsample
if i_level != 0:
conv_block.upsample = Upsample(block_in, resamp_with_conv)
self.conv_blocks.append(conv_block)
# end
self.norm_out = Normalize(block_in, norm_type)
self.conv_out = nn.Conv2d(block_in, out_channels, kernel_size=3, stride=1, padding=1)
@property
def last_layer(self):
return self.conv_out.weight
def forward(self, z):
# z to block_in
h = self.conv_in(z)
# middle
for mid_block in self.mid:
h = mid_block(h)
# upsampling
for i_level, block in enumerate(self.conv_blocks):
for i_block in range(self.num_res_blocks + 1):
h = block.res[i_block](h)
if len(block.attn) > 0:
h = block.attn[i_block](h)
if i_level != self.num_resolutions - 1:
h = block.upsample(h)
# end
h = self.norm_out(h)
h = nonlinearity(h)
h = self.conv_out(h)
return h
class VectorQuantizer(nn.Module):
def __init__(self, n_e, e_dim, beta, entropy_loss_ratio, l2_norm, show_usage):
super().__init__()
self.n_e = n_e
self.e_dim = e_dim
self.beta = beta
self.entropy_loss_ratio = entropy_loss_ratio
self.l2_norm = l2_norm
self.show_usage = show_usage
self.embedding = nn.Embedding(self.n_e, self.e_dim)
self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)
if self.l2_norm:
self.embedding.weight.data = F.normalize(self.embedding.weight.data, p=2, dim=-1)
if self.show_usage:
self.register_buffer("codebook_used", nn.Parameter(torch.zeros(65536)))
def forward(self, z):
# reshape z -> (batch, height, width, channel) and flatten
z = torch.einsum('b c h w -> b h w c', z).contiguous()
z_flattened = z.view(-1, self.e_dim)
# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
if self.l2_norm:
z = F.normalize(z, p=2, dim=-1)
z_flattened = F.normalize(z_flattened, p=2, dim=-1)
embedding = F.normalize(self.embedding.weight, p=2, dim=-1)
else:
embedding = self.embedding.weight
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
torch.sum(embedding**2, dim=1) - 2 * \
torch.einsum('bd,dn->bn', z_flattened, torch.einsum('n d -> d n', embedding))
min_encoding_indices = torch.argmin(d, dim=1)
z_q = embedding[min_encoding_indices].view(z.shape)
perplexity = None
min_encodings = None
vq_loss = None
commit_loss = None
entropy_loss = None
codebook_usage = 0
if self.show_usage and self.training:
cur_len = min_encoding_indices.shape[0]
self.codebook_used[:-cur_len] = self.codebook_used[cur_len:].clone()
self.codebook_used[-cur_len:] = min_encoding_indices
codebook_usage = len(torch.unique(self.codebook_used)) / self.n_e
# compute loss for embedding
if self.training:
vq_loss = torch.mean((z_q - z.detach()) ** 2)
commit_loss = self.beta * torch.mean((z_q.detach() - z) ** 2)
entropy_loss = self.entropy_loss_ratio * compute_entropy_loss(-d)
# preserve gradients
z_q = z + (z_q - z).detach()
# reshape back to match original input shape
z_q = torch.einsum('b h w c -> b c h w', z_q)
return z_q, (vq_loss, commit_loss, entropy_loss, codebook_usage), (perplexity, min_encodings, min_encoding_indices)
def get_codebook_entry(self, indices, shape=None, channel_first=True):
# shape = (batch, channel, height, width) if channel_first else (batch, height, width, channel)
if self.l2_norm:
embedding = F.normalize(self.embedding.weight, p=2, dim=-1)
else:
embedding = self.embedding.weight
z_q = embedding[indices] # (b*h*w, c)
if shape is not None:
if channel_first:
z_q = z_q.reshape(shape[0], shape[2], shape[3], shape[1])
# reshape back to match original input shape
z_q = z_q.permute(0, 3, 1, 2).contiguous()
else:
z_q = z_q.view(shape)
return z_q
class ResnetBlock(nn.Module):
def __init__(self, in_channels, out_channels=None, conv_shortcut=False, dropout=0.0, norm_type='group'):
super().__init__()
self.in_channels = in_channels
out_channels = in_channels if out_channels is None else out_channels
self.out_channels = out_channels
self.use_conv_shortcut = conv_shortcut
self.norm1 = Normalize(in_channels, norm_type)
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.norm2 = Normalize(out_channels, norm_type)
self.dropout = nn.Dropout(dropout)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
if self.in_channels != self.out_channels:
if self.use_conv_shortcut:
self.conv_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
else:
self.nin_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
def forward(self, x):
h = x
h = self.norm1(h)
h = nonlinearity(h)
h = self.conv1(h)
h = self.norm2(h)
h = nonlinearity(h)
h = self.dropout(h)
h = self.conv2(h)
if self.in_channels != self.out_channels:
if self.use_conv_shortcut:
x = self.conv_shortcut(x)
else:
x = self.nin_shortcut(x)
return x+h
class AttnBlock(nn.Module):
def __init__(self, in_channels, norm_type='group'):
super().__init__()
self.norm = Normalize(in_channels, norm_type)
self.q = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
self.k = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
self.v = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
self.proj_out = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
def forward(self, x):
h_ = x
h_ = self.norm(h_)
q = self.q(h_)
k = self.k(h_)
v = self.v(h_)
# compute attention
b,c,h,w = q.shape
q = q.reshape(b,c,h*w)
q = q.permute(0,2,1) # b,hw,c
k = k.reshape(b,c,h*w) # b,c,hw
w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
w_ = w_ * (int(c)**(-0.5))
w_ = F.softmax(w_, dim=2)
# attend to values
v = v.reshape(b,c,h*w)
w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
h_ = h_.reshape(b,c,h,w)
h_ = self.proj_out(h_)
return x+h_
def nonlinearity(x):
# swish
return x*torch.sigmoid(x)
def Normalize(in_channels, norm_type='group'):
assert norm_type in ['group', 'batch']
if norm_type == 'group':
return nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
elif norm_type == 'batch':
return nn.SyncBatchNorm(in_channels)
class Upsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
def forward(self, x):
x = F.interpolate(x, scale_factor=2.0, mode="nearest")
if self.with_conv:
x = self.conv(x)
return x
class Downsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
# no asymmetric padding in torch conv, must do it ourselves
self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
def forward(self, x):
if self.with_conv:
pad = (0,1,0,1)
x = F.pad(x, pad, mode="constant", value=0)
x = self.conv(x)
else:
x = F.avg_pool2d(x, kernel_size=2, stride=2)
return x
def compute_entropy_loss(affinity, loss_type="softmax", temperature=0.01):
flat_affinity = affinity.reshape(-1, affinity.shape[-1])
flat_affinity /= temperature
probs = F.softmax(flat_affinity, dim=-1)
log_probs = F.log_softmax(flat_affinity + 1e-5, dim=-1)
if loss_type == "softmax":
target_probs = probs
else:
raise ValueError("Entropy loss {} not supported".format(loss_type))
avg_probs = torch.mean(target_probs, dim=0)
avg_entropy = - torch.sum(avg_probs * torch.log(avg_probs + 1e-5))
sample_entropy = - torch.mean(torch.sum(target_probs * log_probs, dim=-1))
loss = sample_entropy - avg_entropy
return loss
#################################################################################
# VQ Model Configs #
#################################################################################
def VQ_8(**kwargs):
return VQModel(ModelArgs(encoder_ch_mult=[1, 2, 2, 4], decoder_ch_mult=[1, 2, 2, 4], **kwargs))
def VQ_16(**kwargs):
return VQModel(ModelArgs(encoder_ch_mult=[1, 1, 2, 2, 4], decoder_ch_mult=[1, 1, 2, 2, 4], **kwargs))
VQ_models = {'VQ-16': VQ_16, 'VQ-8': VQ_8}