Download model.py from Astra228/ChudGPT-Femboy: direct link, hf CLI and curl.
- Browser
- Download file 5.44 kB
-
https://huggingface.co/Astra228/ChudGPT-Femboy/resolve/main/model.py
- Command line
-
hf download hf://Astra228/ChudGPT-Femboy/model.py
-
curl -L -o model.py https://huggingface.co/Astra228/ChudGPT-Femboy/resolve/main/model.py
5.44 kB
| """Independently initialized decoder with RoPE, RMSNorm, SwiGLU and KV cache.""" | |
| from dataclasses import dataclass, asdict | |
| import time | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| class Config: | |
| vocab_size: int = 8192 | |
| dim: int = 384 | |
| layers: int = 12 | |
| heads: int = 6 | |
| ff: int = 1408 | |
| context: int = 2048 | |
| class RMSNorm(nn.Module): | |
| def __init__(self, dim): | |
| super().__init__() | |
| self.weight = nn.Parameter(torch.ones(dim)) | |
| def forward(self, x): | |
| return (x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + 1e-6)).to(x.dtype) * self.weight | |
| class Block(nn.Module): | |
| def __init__(self, c): | |
| super().__init__() | |
| self.c = c | |
| self.n1, self.n2 = RMSNorm(c.dim), RMSNorm(c.dim) | |
| self.qkv = nn.Linear(c.dim, c.dim * 3, bias=False) | |
| self.out = nn.Linear(c.dim, c.dim, bias=False) | |
| self.gate = nn.Linear(c.dim, c.ff, bias=False) | |
| self.up = nn.Linear(c.dim, c.ff, bias=False) | |
| self.down = nn.Linear(c.ff, c.dim, bias=False) | |
| self.register_buffer('freq', 1 / (10000 ** (torch.arange(0, c.dim // c.heads, 2).float() / (c.dim // c.heads))), persistent=False) | |
| def forward(self, x, past=None): | |
| b, t, d = x.shape | |
| q, k, v = [z.view(b, t, self.c.heads, d // self.c.heads).transpose(1, 2) for z in self.qkv(self.n1(x)).chunk(3, -1)] | |
| offset = 0 if past is None else past[0].shape[-2] | |
| angles = torch.outer(torch.arange(offset, offset+t, device=x.device), self.freq) | |
| cos, sin = angles.cos().to(q.dtype), angles.sin().to(q.dtype) | |
| def rotate(z): | |
| a, b = z[..., 0::2], z[..., 1::2] | |
| return torch.stack((a*cos-b*sin, a*sin+b*cos), -1).flatten(-2) | |
| q, k = rotate(q), rotate(k) | |
| if past is not None: | |
| k, v = torch.cat((past[0], k), -2), torch.cat((past[1], v), -2) | |
| if past is None: | |
| a = F.scaled_dot_product_attention(q, k, v, is_causal=True) | |
| elif t==1: | |
| a = F.scaled_dot_product_attention(q, k, v) | |
| else: | |
| mask = torch.arange(k.shape[-2], device=x.device)[None, :] <= torch.arange(offset, offset+t, device=x.device)[:, None] | |
| a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) | |
| x = x + self.out(a.transpose(1, 2).reshape(b, t, d)) | |
| z = self.n2(x) | |
| return x + self.down(F.silu(self.gate(z))*self.up(z)), (k, v) | |
| class Model(nn.Module): | |
| def __init__(self, c=Config()): | |
| super().__init__() | |
| if c.dim % c.heads or (c.dim//c.heads) % 2 or min(asdict(c).values()) <= 0: | |
| raise ValueError('Invalid model dimensions') | |
| self.config = c | |
| self.embedding = nn.Embedding(c.vocab_size, c.dim) | |
| self.blocks = nn.ModuleList(Block(c) for _ in range(c.layers)) | |
| self.norm = RMSNorm(c.dim) | |
| self.head = nn.Linear(c.dim, c.vocab_size, bias=False) | |
| self.head.weight = self.embedding.weight | |
| self.apply(self._init) | |
| def _init(m): | |
| if isinstance(m, (nn.Linear, nn.Embedding)): | |
| nn.init.normal_(m.weight, std=0.02) | |
| def forward(self, ids, past=None): | |
| offset = 0 if past is None else past[0][0].shape[-2] | |
| if ids.shape[1]+offset > self.config.context: | |
| raise ValueError('Context window exceeded') | |
| x, cache = self.embedding(ids), [] | |
| for i, block in enumerate(self.blocks): | |
| x, kv = block(x, None if past is None else past[i]) | |
| cache.append(kv) | |
| return self.head(self.norm(x)), cache | |
| def generate(model, ids, max_tokens=128, temperature=.8, top_k=40, top_p=.95, repetition_penalty=1.1, eos=None, stop_ids=(), timeout=60, valid_vocab_size=None): | |
| if temperature < 0 or top_k < 0 or not 0 < top_p <= 1 or repetition_penalty < 1: | |
| raise ValueError('Invalid sampling controls') | |
| model.eval() | |
| past, current, result = None, ids, ids[0].tolist() | |
| deadline = time.monotonic()+timeout | |
| for _ in range(min(max_tokens, model.config.context-ids.shape[1])): | |
| if time.monotonic()>deadline: raise TimeoutError('Generation timed out') | |
| logits, past = model(current, past) | |
| scores = logits[:, -1].float() | |
| if valid_vocab_size is not None: | |
| if not 1 <= valid_vocab_size <= scores.shape[-1]: raise ValueError('Invalid tokenizer vocabulary size') | |
| scores[:, valid_vocab_size:] = -float('inf') | |
| seen = list(set(result)) | |
| scores[:, seen] = torch.where(scores[:, seen] < 0, scores[:, seen]*repetition_penalty, scores[:, seen]/repetition_penalty) | |
| if temperature == 0: | |
| token = scores.argmax(-1, keepdim=True) | |
| else: | |
| scores /= temperature | |
| if top_k: | |
| scores[scores < scores.topk(min(top_k, scores.shape[-1])).values[:, -1:]] = -float('inf') | |
| ordered, indices = scores.sort(descending=True) | |
| remove = ordered.softmax(-1).cumsum(-1) > top_p | |
| remove[:, 1:] = remove[:, :-1].clone() | |
| remove[:, 0] = False | |
| ordered[remove] = -float('inf') | |
| token = indices.gather(-1, torch.multinomial(ordered.softmax(-1), 1)) | |
| value = token.item() | |
| result.append(value) | |
| if value == eos or any(result[-len(s):] == list(s) for s in stop_ids if s): | |
| break | |
| current = token | |
| return result[ids.shape[1]:] | |