Download model.py from SOYORiN/Susu: direct link, hf CLI and curl.
- Browser
- Download file 8.09 kB
-
https://huggingface.co/SOYORiN/Susu/resolve/main/model.py
- Command line
-
hf download hf://SOYORiN/Susu/model.py
-
curl -L -o model.py https://huggingface.co/SOYORiN/Susu/resolve/main/model.py
8.09 kB
| """Susu-Micro causal LM. Explicit shared weights; independent per-depth KV caches. | |
| Right-padded independent sequences only. No cross-document packing. Training | |
| uses torch SDPA; K/V replication is an intentionally portable GQA baseline. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass, asdict | |
| import math | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| class Config: | |
| vocab_size: int = 6144 | |
| hidden: int = 384 | |
| ffn: int = 1024 | |
| layers: int = 5 | |
| q_heads: int = 6 | |
| kv_heads: int = 2 | |
| head_dim: int = 64 | |
| repeats: int = 1 | |
| context: int = 2048 | |
| rope_theta: float = 10000.0 | |
| eps: float = 1e-6 | |
| def __post_init__(self): | |
| for name in ('vocab_size','hidden','ffn','layers','q_heads','kv_heads','head_dim','repeats','context'): | |
| if not isinstance(getattr(self, name), int) or getattr(self, name) <= 0: | |
| raise ValueError(f'{name} must be a positive integer') | |
| if self.hidden != self.q_heads * self.head_dim or self.q_heads % self.kv_heads: | |
| raise ValueError('Invalid GQA head sizes') | |
| if self.head_dim % 2 or self.rope_theta <= 1 or self.eps <= 0: | |
| raise ValueError('Invalid RoPE/norm configuration') | |
| def parameter_count(self): | |
| d, f, h, k = self.hidden, self.ffn, self.head_dim, self.kv_heads | |
| return self.vocab_size*d + self.layers*(2*d*d+2*d*k*h+3*d*f+2*d+2*h)+d | |
| class RMSNorm(nn.Module): | |
| def __init__(self, d, eps): | |
| super().__init__() | |
| self.weight = nn.Parameter(torch.ones(d)) | |
| self.eps = eps | |
| def forward(self, x): | |
| z = x.float() | |
| return (z * torch.rsqrt(z.square().mean(-1,keepdim=True)+self.eps) * self.weight.float()).to(x.dtype) | |
| def rope(x, cos, sin): | |
| a, b = x.chunk(2, -1) | |
| return x*cos + torch.cat((-b,a),-1)*sin | |
| class Attention(nn.Module): | |
| def __init__(self, c): | |
| super().__init__(); self.c = c | |
| self.q = nn.Linear(c.hidden,c.hidden,bias=False) | |
| self.k = nn.Linear(c.hidden,c.kv_heads*c.head_dim,bias=False) | |
| self.v = nn.Linear(c.hidden,c.kv_heads*c.head_dim,bias=False) | |
| self.o = nn.Linear(c.hidden,c.hidden,bias=False) | |
| self.qn = RMSNorm(c.head_dim,c.eps); self.kn = RMSNorm(c.head_dim,c.eps) | |
| def forward(self, x, cos, sin, past=None, cache=False): | |
| b,t,_ = x.shape; c = self.c | |
| q = self.qn(self.q(x).view(b,t,c.q_heads,c.head_dim)).transpose(1,2) | |
| k = self.kn(self.k(x).view(b,t,c.kv_heads,c.head_dim)).transpose(1,2) | |
| v = self.v(x).view(b,t,c.kv_heads,c.head_dim).transpose(1,2) | |
| q,k = rope(q,cos,sin),rope(k,cos,sin) | |
| prefix = 0 | |
| if past is not None: | |
| prefix = past[0].shape[2] | |
| if past[0].shape != past[1].shape or past[0].shape[:2] != (b,c.kv_heads): | |
| raise ValueError('Malformed cache') | |
| k = torch.cat((past[0],k),2); v = torch.cat((past[1],v),2) | |
| groups = c.q_heads // c.kv_heads | |
| kh,vh = k.repeat_interleave(groups,1),v.repeat_interleave(groups,1) | |
| if prefix == 0: | |
| y = F.scaled_dot_product_attention(q,kh,vh,dropout_p=0.0,is_causal=True) | |
| elif t == 1: | |
| # is_causal=True would use the wrong upper-left mask during decoding. | |
| y = F.scaled_dot_product_attention(q,kh,vh,dropout_p=0.0,is_causal=False) | |
| else: | |
| query = torch.arange(prefix,prefix+t,device=x.device)[:,None] | |
| key = torch.arange(prefix+t,device=x.device)[None,:] | |
| y = F.scaled_dot_product_attention(q,kh,vh,attn_mask=key<=query,dropout_p=0.0) | |
| y = self.o(y.transpose(1,2).contiguous().view(b,t,c.hidden)) | |
| return y, (k.detach(),v.detach()) if cache else None | |
| class Block(nn.Module): | |
| def __init__(self,c): | |
| super().__init__() | |
| self.n1=RMSNorm(c.hidden,c.eps); self.n2=RMSNorm(c.hidden,c.eps) | |
| self.attn=Attention(c) | |
| self.gate=nn.Linear(c.hidden,c.ffn,bias=False) | |
| self.up=nn.Linear(c.hidden,c.ffn,bias=False) | |
| self.down=nn.Linear(c.ffn,c.hidden,bias=False) | |
| def forward(self,x,cos,sin,past=None,cache=False): | |
| y,kv=self.attn(self.n1(x),cos,sin,past,cache) | |
| x=x+y; z=self.n2(x) | |
| return x+self.down(F.silu(self.gate(z))*self.up(z)),kv | |
| class MicroLM(nn.Module): | |
| def __init__(self,c:Config): | |
| super().__init__(); self.config=c | |
| self.embedding=nn.Embedding(c.vocab_size,c.hidden) | |
| self.blocks=nn.ModuleList(Block(c) for _ in range(c.layers)) | |
| self.norm=RMSNorm(c.hidden,c.eps) | |
| self.apply(self._init) | |
| for block in self.blocks: | |
| std=0.02/math.sqrt(2*c.layers*c.repeats) | |
| nn.init.normal_(block.attn.o.weight,std=std) | |
| nn.init.normal_(block.down.weight,std=std) | |
| if sum(p.numel() for p in self.parameters()) != c.parameter_count(): | |
| raise RuntimeError('Analytic and actual parameter counts differ') | |
| def _init(m): | |
| if isinstance(m,(nn.Embedding,nn.Linear)): | |
| nn.init.normal_(m.weight,std=0.02) | |
| def forward(self, ids, past=None, use_cache=False, last_only=False): | |
| if ids.ndim != 2 or ids.shape[1]<1 or ids.dtype != torch.long: | |
| raise ValueError('Expected nonempty [batch,tokens] LongTensor') | |
| if self.training and (use_cache or past is not None): | |
| raise ValueError('Cache is inference-only') | |
| c=self.config; start=0 | |
| if past is not None: | |
| if len(past)!=c.layers*c.repeats: | |
| raise ValueError('Each executed layer needs its own cache') | |
| lengths={kv[0].shape[2] for kv in past} | |
| if len(lengths)!=1: raise ValueError('Inconsistent cache lengths') | |
| start=next(iter(lengths)) | |
| if start+ids.shape[1]>c.context: raise ValueError('Context exceeded') | |
| x=self.embedding(ids) | |
| inv=c.rope_theta**(-torch.arange(0,c.head_dim,2,device=x.device,dtype=torch.float32)/c.head_dim) | |
| phase=torch.arange(start,start+ids.shape[1],device=x.device,dtype=torch.float32)[:,None]*inv[None,:] | |
| phase=torch.cat((phase,phase),-1)[None,None,:,:] | |
| cos,sin=phase.cos().to(x.dtype),phase.sin().to(x.dtype) | |
| caches=[]; depth=0 | |
| for block in self.blocks: | |
| for _ in range(c.repeats): | |
| x,kv=block(x,cos,sin,None if past is None else past[depth],use_cache) | |
| if use_cache: caches.append(kv) | |
| depth+=1 | |
| if last_only: x=x[:,-1:] | |
| return F.linear(self.norm(x),self.embedding.weight), (caches if use_cache else None) | |
| def generate(self, ids, max_new_tokens=96, temperature=0.7, top_p=0.9, | |
| eos_id=2, forbidden_ids=(), active_vocab=None, generator=None): | |
| if self.training: raise ValueError('Call eval() before generate()') | |
| if ids.shape[0]!=1: raise ValueError('Interactive generation is batch=1') | |
| if max_new_tokens<1 or not 0<top_p<=1 or temperature<0: raise ValueError('Invalid generation settings') | |
| if ids.shape[1]+max_new_tokens>self.config.context: raise ValueError('Output would exceed context') | |
| result=[]; current=ids; kv=None; stopped=False | |
| for _ in range(max_new_tokens): | |
| out,kv=self(current,past=kv,use_cache=True,last_only=True) | |
| scores=out[0,-1].float() | |
| if active_vocab is not None: scores[active_vocab:]=-torch.inf | |
| if forbidden_ids: scores[list(forbidden_ids)]=-torch.inf | |
| if temperature==0: token=scores.argmax() | |
| else: | |
| probs=torch.softmax(scores/temperature,-1) | |
| ordered,indices=probs.sort(descending=True) | |
| remove=ordered.cumsum(0)-ordered>top_p | |
| ordered[remove]=0; ordered=ordered/ordered.sum() | |
| token=indices[torch.multinomial(ordered,1,generator=generator)[0]] | |
| value=int(token); result.append(value) | |
| if value==eos_id: stopped=True; break | |
| current=token.reshape(1,1).to(dtype=torch.long) | |
| return result,stopped | |