Download guru/model.py from velkatomka/Axapaxa.Model-Ferrum-1-Base: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/velkatomka/Axapaxa.Model-Ferrum-1-Base/resolve/main/guru/model.py
- Command line
-
hf download hf://velkatomka/Axapaxa.Model-Ferrum-1-Base/guru/model.py
-
curl -L -o model.py https://huggingface.co/velkatomka/Axapaxa.Model-Ferrum-1-Base/resolve/main/guru/model.py
10.2 kB
| """Decoder-only Transformer: RoPE, GQA, RMSNorm, SwiGLU, QK-norm, tied embeddings, bez biasů. | |
| Multimodalita: jeden slovník = [text tokeny | obrazové kódy VQ-VAE]. Při tréninku i generování | |
| se text a obraz softmaxují ODDĚLENĚ (obrazový cíl -> softmax jen přes obrazové kódy a naopak). | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from dataclasses import asdict, dataclass | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from torch.utils.checkpoint import checkpoint | |
| from . import config as C | |
| _HAS_GQA = tuple(int(x) for x in torch.__version__.split("+")[0].split(".")[:2]) >= (2, 5) | |
| class ModelConfig: | |
| n_layer: int = 12 | |
| d_model: int = 768 | |
| n_head: int = 12 | |
| n_kv_head: int = 4 | |
| d_ff: int = 2048 | |
| max_seq: int = 1024 | |
| text_vocab: int = 32000 | |
| img_codes: int = 8192 | |
| vocab: int = 40192 | |
| rope_theta: float = 10000.0 | |
| grad_ckpt: bool = False | |
| def head_dim(self) -> int: | |
| return self.d_model // self.n_head | |
| def make_config(preset: str, layout: C.Layout) -> ModelConfig: | |
| p = dict(C.MODEL_PRESETS[preset]) | |
| return ModelConfig(**p, text_vocab=layout.text_vocab, img_codes=layout.img_codes, vocab=layout.vocab) | |
| class RMSNorm(nn.Module): | |
| def __init__(self, d: int, eps: float = 1e-6): | |
| super().__init__() | |
| self.w = nn.Parameter(torch.ones(d)) | |
| self.eps = eps | |
| def forward(self, x): | |
| y = x.float() | |
| y = y * torch.rsqrt(y.pow(2).mean(-1, keepdim=True) + self.eps) | |
| return (y * self.w.float()).to(x.dtype) | |
| def rope_tables(head_dim: int, max_seq: int, theta: float): | |
| inv = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim)) | |
| fr = torch.outer(torch.arange(max_seq).float(), inv) | |
| return fr.cos(), fr.sin() | |
| def apply_rope(x, cos, sin): | |
| # x: (B,H,T,hd); cos/sin: (T,hd/2) | |
| h = x.size(-1) // 2 | |
| x1, x2 = x[..., :h], x[..., h:] | |
| cos = cos.to(x.dtype)[None, None] | |
| sin = sin.to(x.dtype)[None, None] | |
| return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1) | |
| def sdpa(q, k, v): | |
| """Kauzální attention; funguje pro trénink (Tq==Tk), dekódování (Tq==1) i pokračování s cache.""" | |
| kw = {} | |
| if q.size(1) != k.size(1): | |
| if _HAS_GQA: | |
| kw["enable_gqa"] = True | |
| else: | |
| r = q.size(1) // k.size(1) | |
| k, v = k.repeat_interleave(r, 1), v.repeat_interleave(r, 1) | |
| tq, tk = q.size(2), k.size(2) | |
| if tq == tk: | |
| return F.scaled_dot_product_attention(q, k, v, is_causal=True, **kw) | |
| if tq == 1: | |
| return F.scaled_dot_product_attention(q, k, v, **kw) | |
| mask = torch.ones(tq, tk, dtype=torch.bool, device=q.device).tril(diagonal=tk - tq) | |
| return F.scaled_dot_product_attention(q, k, v, attn_mask=mask, **kw) | |
| class KVCache: | |
| def __init__(self, cfg: ModelConfig, batch: int, max_len: int, device, dtype): | |
| shp = (batch, cfg.n_kv_head, max_len, cfg.head_dim) | |
| self.k = [torch.zeros(shp, device=device, dtype=dtype) for _ in range(cfg.n_layer)] | |
| self.v = [torch.zeros(shp, device=device, dtype=dtype) for _ in range(cfg.n_layer)] | |
| self.pos = 0 | |
| self.max_len = max_len | |
| def update(self, i, k, v): | |
| t = k.size(2) | |
| self.k[i][:, :, self.pos:self.pos + t] = k | |
| self.v[i][:, :, self.pos:self.pos + t] = v | |
| return self.k[i][:, :, :self.pos + t], self.v[i][:, :, :self.pos + t] | |
| class Attention(nn.Module): | |
| def __init__(self, c: ModelConfig): | |
| super().__init__() | |
| self.c = c | |
| hd = c.head_dim | |
| self.q = nn.Linear(c.d_model, c.n_head * hd, bias=False) | |
| self.k = nn.Linear(c.d_model, c.n_kv_head * hd, bias=False) | |
| self.v = nn.Linear(c.d_model, c.n_kv_head * hd, bias=False) | |
| self.o = nn.Linear(c.n_head * hd, c.d_model, bias=False) | |
| self.qn = RMSNorm(hd) | |
| self.kn = RMSNorm(hd) | |
| def forward(self, x, cos, sin, cache=None, layer=0): | |
| c = self.c | |
| B, T, _ = x.shape | |
| q = self.q(x).view(B, T, c.n_head, c.head_dim).transpose(1, 2) | |
| k = self.k(x).view(B, T, c.n_kv_head, c.head_dim).transpose(1, 2) | |
| v = self.v(x).view(B, T, c.n_kv_head, c.head_dim).transpose(1, 2) | |
| q, k = apply_rope(self.qn(q), cos, sin), apply_rope(self.kn(k), cos, sin) | |
| if cache is not None: | |
| k, v = cache.update(layer, k, v) | |
| y = sdpa(q, k, v).transpose(1, 2).reshape(B, T, -1) | |
| return self.o(y) | |
| class MLP(nn.Module): | |
| def __init__(self, c: ModelConfig): | |
| super().__init__() | |
| self.gate = nn.Linear(c.d_model, c.d_ff, bias=False) | |
| self.up = nn.Linear(c.d_model, c.d_ff, bias=False) | |
| self.down = nn.Linear(c.d_ff, c.d_model, bias=False) | |
| def forward(self, x): | |
| return self.down(F.silu(self.gate(x)) * self.up(x)) | |
| class Block(nn.Module): | |
| def __init__(self, c: ModelConfig): | |
| super().__init__() | |
| self.n1, self.n2 = RMSNorm(c.d_model), RMSNorm(c.d_model) | |
| self.attn, self.mlp = Attention(c), MLP(c) | |
| def forward(self, x, cos, sin, cache=None, layer=0): | |
| x = x + self.attn(self.n1(x), cos, sin, cache, layer) | |
| return x + self.mlp(self.n2(x)) | |
| class GPT(nn.Module): | |
| def __init__(self, cfg: ModelConfig): | |
| super().__init__() | |
| self.cfg = cfg | |
| self.emb = nn.Embedding(cfg.vocab, cfg.d_model) | |
| self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layer)]) | |
| self.norm = RMSNorm(cfg.d_model) | |
| cos, sin = rope_tables(cfg.head_dim, cfg.max_seq, cfg.rope_theta) | |
| self.register_buffer("cos", cos, persistent=False) | |
| self.register_buffer("sin", sin, persistent=False) | |
| self.apply(self._init) | |
| s = 0.02 / math.sqrt(2 * cfg.n_layer) | |
| for b in self.blocks: | |
| nn.init.normal_(b.attn.o.weight, std=s) | |
| nn.init.normal_(b.mlp.down.weight, std=s) | |
| def _init(m): | |
| if isinstance(m, (nn.Linear, nn.Embedding)): | |
| nn.init.normal_(m.weight, std=0.02) | |
| def n_params(self) -> int: | |
| return sum(p.numel() for p in self.parameters()) | |
| # ---- dopředný průchod ------------------------------------------------- | |
| def hidden(self, idx, cache: KVCache | None = None): | |
| T = idx.size(1) | |
| pos = cache.pos if cache is not None else 0 | |
| x = self.emb(idx) | |
| cos, sin = self.cos[pos:pos + T], self.sin[pos:pos + T] | |
| for i, blk in enumerate(self.blocks): | |
| if self.training and self.cfg.grad_ckpt and cache is None: | |
| x = checkpoint(blk, x, cos, sin, use_reentrant=False) | |
| else: | |
| x = blk(x, cos, sin, cache, i) | |
| return self.norm(x) | |
| def step(self, idx, cache: KVCache): | |
| """Pro generování: vrátí logity poslední pozice (B,V) a posune cache.""" | |
| h = self.hidden(idx, cache) | |
| cache.pos += idx.size(1) | |
| return F.linear(h[:, -1], self.emb.weight) | |
| # ---- loss (text a obraz se softmaxují odděleně, po částech kvůli paměti) ---- | |
| def _chunk_loss(self, hc, yc): | |
| tv, nc = self.cfg.text_vocab, self.cfg.img_codes | |
| logits = F.linear(hc, self.emb.weight).float() | |
| is_img = yc >= tv | |
| lt, li = logits[:, :tv], logits[:, tv:tv + nc] | |
| lse_t, lse_i = torch.logsumexp(lt, -1), torch.logsumexp(li, -1) | |
| zero = torch.zeros_like(yc) | |
| tgt_t = torch.where(is_img, zero, yc) | |
| tgt_i = torch.where(is_img, yc - tv, zero) | |
| nll_t = (lse_t - lt.gather(1, tgt_t[:, None]).squeeze(1)) * (~is_img) | |
| nll_i = (lse_i - li.gather(1, tgt_i[:, None]).squeeze(1)) * is_img | |
| z = lse_t.pow(2) * (~is_img) + lse_i.pow(2) * is_img | |
| return nll_t.sum(), nll_i.sum(), z.sum() | |
| def loss(self, h, y, img_w: float = 0.5, z_w: float = 1e-4, chunk: int = 4096): | |
| h = h.reshape(-1, h.size(-1)) | |
| y = y.reshape(-1) | |
| valid = y >= 0 | |
| h, y = h[valid], y[valid] | |
| tv = self.cfg.text_vocab | |
| n_i = (y >= tv).sum().float() | |
| n_t = y.numel() - n_i | |
| st = si = sz = h.new_zeros((), dtype=torch.float32) | |
| for s in range(0, y.numel(), chunk): | |
| a, b, z = checkpoint(self._chunk_loss, h[s:s + chunk], y[s:s + chunk], use_reentrant=False) | |
| st, si, sz = st + a, si + b, sz + z | |
| denom = (n_t + img_w * n_i).clamp(min=1.0) | |
| loss = (st + img_w * si + z_w * sz) / denom | |
| return loss, (st.detach() / n_t.clamp(min=1.0), si.detach() / n_i.clamp(min=1.0), n_t, n_i) | |
| def token_logp(self, h, y): | |
| """Logaritmická pravděpodobnost každého cíle (B,T); 0 kde y==-100. Pro DPO.""" | |
| tv, nc = self.cfg.text_vocab, self.cfg.img_codes | |
| logits = F.linear(h, self.emb.weight).float() | |
| is_img = y >= tv | |
| lt = logits[..., :tv].log_softmax(-1) | |
| li = logits[..., tv:tv + nc].log_softmax(-1) | |
| zero = torch.zeros_like(y) | |
| tgt_t = torch.where(is_img | (y < 0), zero, y) | |
| tgt_i = torch.where(is_img, y - tv, zero) | |
| lp = torch.where(is_img, li.gather(-1, tgt_i.unsqueeze(-1)).squeeze(-1), | |
| lt.gather(-1, tgt_t.unsqueeze(-1)).squeeze(-1)) | |
| return lp * (y >= 0) | |
| # ---------------------------------------------------------------------------- | |
| # Ukládání / načítání hotových modelů (models/*.pt) | |
| # ---------------------------------------------------------------------------- | |
| def save_model(path, model: GPT, layout: C.Layout, meta: dict): | |
| import os | |
| from dataclasses import asdict as _a | |
| sd = {k: v.detach().to(torch.bfloat16).cpu() for k, v in model.state_dict().items()} | |
| tmp = str(path) + ".tmp" | |
| with open(tmp, "wb") as f: | |
| torch.save({"config": _a(model.cfg), "layout": _a(layout), "weights": sd, "meta": meta}, f) | |
| f.flush() | |
| os.fsync(f.fileno()) | |
| os.replace(tmp, path) | |
| def load_model(path, device="cpu", dtype=torch.float32): | |
| blob = torch.load(path, map_location="cpu", weights_only=False) | |
| cfg = ModelConfig(**blob["config"]) | |
| cfg.grad_ckpt = False | |
| m = GPT(cfg) | |
| m.load_state_dict({k: v.float() for k, v in blob["weights"].items()}, strict=True) | |
| return m.to(device=device, dtype=dtype).eval(), blob.get("layout"), blob.get("meta", {}) | |