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:
1 parent
da8e9e95c8
commit
003c78f669
11 files changed
+1884
No files matched your search
+280
@@ -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
|
||||
Reference in new issue
Block a user