unkony's picture
sync code
c105f80 verified
Raw History Blame Contribute Delete
5.32 kB
"""Elyon-LM: небольшая decoder-only модель в стиле Llama (RMSNorm, RoPE, SwiGLU, общие эмбеддинги)."""
from __future__ import annotations
import math
from dataclasses import dataclass
import torch
import torch.nn as nn
import torch.nn.functional as F
@dataclass
class ModelConfig:
vocab_size: int = 8192
n_layer: int = 4
n_head: int = 4
d_model: int = 256
ctx: int = 256
ffn_mult: float = 8 / 3
rope_base: float = 10000.0
n_loops: int = 1 # сколько раз подряд проходим один и тот же набор из n_layer слоёв (общие веса)
@property
def ffn_hidden(self) -> int:
return max(32, int(round(self.d_model * self.ffn_mult / 32)) * 32)
class RMSNorm(nn.Module):
def __init__(self, d: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(d))
def forward(self, x):
xf = x.float()
xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)
return xf.type_as(x) * self.weight
def rope_cache(ctx: int, head_dim: int, base: float):
inv = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
freqs = torch.outer(torch.arange(ctx).float(), inv)
return freqs.cos(), freqs.sin()
def apply_rope(x, cos, sin):
# x: (B, H, T, hd); cos/sin: (ctx, hd/2)
t = x.size(2)
c, s = cos[:t], sin[:t]
x1, x2 = x[..., 0::2], x[..., 1::2]
out = torch.stack((x1 * c - x2 * s, x1 * s + x2 * c), dim=-1).flatten(-2)
return out.type_as(x)
class Attention(nn.Module):
def __init__(self, c: ModelConfig):
super().__init__()
assert c.d_model % c.n_head == 0
self.h = c.n_head
self.hd = c.d_model // c.n_head
assert self.hd % 2 == 0
self.qkv = nn.Linear(c.d_model, 3 * c.d_model, bias=False)
self.proj = nn.Linear(c.d_model, c.d_model, bias=False)
def forward(self, x, cos, sin):
b, t, d = x.shape
q, k, v = self.qkv(x).view(b, t, 3, self.h, self.hd).permute(2, 0, 3, 1, 4)
q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return self.proj(y.transpose(1, 2).reshape(b, t, d))
class SwiGLU(nn.Module):
def __init__(self, c: ModelConfig):
super().__init__()
self.gate = nn.Linear(c.d_model, c.ffn_hidden, bias=False)
self.up = nn.Linear(c.d_model, c.ffn_hidden, bias=False)
self.down = nn.Linear(c.ffn_hidden, 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.attn = RMSNorm(c.d_model), Attention(c)
self.n2, self.mlp = RMSNorm(c.d_model), SwiGLU(c)
def forward(self, x, cos, sin):
x = x + self.attn(self.n1(x), cos, sin)
return x + self.mlp(self.n2(x))
class GPT(nn.Module):
def __init__(self, c: ModelConfig):
super().__init__()
self.c = c
self.tok = nn.Embedding(c.vocab_size, c.d_model)
self.blocks = nn.ModuleList(Block(c) for _ in range(c.n_layer))
self.norm = RMSNorm(c.d_model)
self.head = nn.Linear(c.d_model, c.vocab_size, bias=False)
self.head.weight = self.tok.weight # общие веса
cos, sin = rope_cache(c.ctx, c.d_model // c.n_head, c.rope_base)
self.register_buffer("cos", cos, persistent=False)
self.register_buffer("sin", sin, persistent=False)
self.apply(self._init)
for name, p in self.named_parameters():
if name.endswith("proj.weight") or name.endswith("down.weight"):
nn.init.normal_(p, 0.0, 0.02 / math.sqrt(2 * c.n_layer * c.n_loops))
@staticmethod
def _init(m):
if isinstance(m, (nn.Linear, nn.Embedding)):
nn.init.normal_(m.weight, 0.0, 0.02)
def num_params(self) -> int:
return sum(p.numel() for p in self.parameters())
def forward(self, idx, targets=None):
assert idx.size(1) <= self.c.ctx, "последовательность длиннее контекста"
x = self.tok(idx)
for _ in range(self.c.n_loops):
for blk in self.blocks:
x = blk(x, self.cos, self.sin)
logits = self.head(self.norm(x))
loss = None
if targets is not None:
loss = F.cross_entropy(logits.float().view(-1, logits.size(-1)), targets.reshape(-1))
return logits, loss
@torch.no_grad()
def generate(self, idx, max_new: int, temperature: float = 0.8, top_k: int = 40):
for _ in range(max_new):
logits, _ = self(idx[:, -self.c.ctx:])
logits = logits[:, -1, :].float() / max(temperature, 1e-5)
if top_k:
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
logits[logits < v[:, [-1]]] = -float("inf")
nxt = torch.multinomial(F.softmax(logits, dim=-1), 1)
idx = torch.cat([idx, nxt], dim=1)
return idx