bugscope-2.35b / model.py
HapiDev's picture
Upload model.py with huggingface_hub
c4ea538 verified
Raw History Blame Contribute Delete
6.24 kB
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from config import BugScopeConfig
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(dim))
self.eps = eps
def forward(self, x):
norm = x.float().pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
return (x.float() * norm).type_as(x) * self.weight
def precompute_rope_freqs(dim, max_len, theta=10000.0, device=None):
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, device=device).float() / dim))
t = torch.arange(max_len, device=device).float()
freqs = torch.outer(t, freqs)
return torch.polar(torch.ones_like(freqs), freqs)
def apply_rope(xq, xk, freqs):
Bq, Hq, Tq, Dq = xq.shape
Bk, Hk, Tk, Dk = xk.shape
xq_c = torch.view_as_complex(xq.float().reshape(Bq, Hq, Tq, Dq // 2, 2))
xk_c = torch.view_as_complex(xk.float().reshape(Bk, Hk, Tk, Dk // 2, 2))
f = freqs[:Tq].unsqueeze(0).unsqueeze(0)
xq_out = torch.view_as_real(xq_c * f).reshape(Bq, Hq, Tq, Dq)
xk_out = torch.view_as_real(xk_c * f).reshape(Bk, Hk, Tk, Dk)
return xq_out.type_as(xq), xk_out.type_as(xk)
class GQAttention(nn.Module):
def __init__(self, cfg):
super().__init__()
self.n_heads = cfg.n_heads
self.n_kv_heads = cfg.n_kv_heads
self.head_dim = cfg.head_dim()
self.n_rep = cfg.n_heads // cfg.n_kv_heads
self.wq = nn.Linear(cfg.hidden_dim, cfg.n_heads * self.head_dim, bias=False)
self.wk = nn.Linear(cfg.hidden_dim, cfg.n_kv_heads * self.head_dim, bias=False)
self.wv = nn.Linear(cfg.hidden_dim, cfg.n_kv_heads * self.head_dim, bias=False)
self.wo = nn.Linear(cfg.n_heads * self.head_dim, cfg.hidden_dim, bias=False)
self.attn_dropout = nn.Dropout(cfg.dropout)
def forward(self, x, freqs, mask=None, kv_cache=None):
B, T, _ = x.shape
q = self.wq(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
k = self.wk(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
v = self.wv(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
q, k = apply_rope(q, k, freqs)
if kv_cache is not None:
k = torch.cat([kv_cache[0], k], dim=2)
v = torch.cat([kv_cache[1], v], dim=2)
new_cache = (k, v)
if self.n_rep > 1:
k = k.repeat_interleave(self.n_rep, dim=1)
v = v.repeat_interleave(self.n_rep, dim=1)
out = F.scaled_dot_product_attention(
q, k, v, attn_mask=mask,
dropout_p=self.attn_dropout.p if self.training else 0.0,
is_causal=(mask is None))
out = out.transpose(1, 2).contiguous().view(B, T, -1)
return self.wo(out), new_cache
class SwiGLUFFN(nn.Module):
def __init__(self, cfg):
super().__init__()
self.w_gate = nn.Linear(cfg.hidden_dim, cfg.ffn_dim, bias=False)
self.w_up = nn.Linear(cfg.hidden_dim, cfg.ffn_dim, bias=False)
self.w_down = nn.Linear(cfg.ffn_dim, cfg.hidden_dim, bias=False)
self.dropout = nn.Dropout(cfg.dropout)
def forward(self, x):
return self.dropout(self.w_down(F.silu(self.w_gate(x)) * self.w_up(x)))
class TransformerBlock(nn.Module):
def __init__(self, cfg):
super().__init__()
self.attn_norm = RMSNorm(cfg.hidden_dim)
self.attn = GQAttention(cfg)
self.ffn_norm = RMSNorm(cfg.hidden_dim)
self.ffn = SwiGLUFFN(cfg)
def forward(self, x, freqs, mask=None, kv_cache=None):
h, cache = self.attn(self.attn_norm(x), freqs, mask, kv_cache)
x = x + h
x = x + self.ffn(self.ffn_norm(x))
return x, cache
class BugScopeModel(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.hidden_dim)
self.layers = nn.ModuleList([TransformerBlock(cfg) for _ in range(cfg.n_layers)])
self.norm = RMSNorm(cfg.hidden_dim)
self.lm_head = nn.Linear(cfg.hidden_dim, cfg.vocab_size, bias=False)
self.lm_head.weight = self.tok_emb.weight
self.register_buffer("rope_freqs",
precompute_rope_freqs(cfg.head_dim(), cfg.max_seq_len, cfg.rope_theta),
persistent=False)
self.apply(self._init_weights)
for pn, p in self.named_parameters():
if pn.endswith("wo.weight") or pn.endswith("w_down.weight"):
nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * cfg.n_layers))
def _init_weights(self, module):
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None: nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=0.0, std=0.02)
def forward(self, input_ids, targets=None, kv_caches=None):
B, T = input_ids.shape
x = self.tok_emb(input_ids)
if kv_caches is not None and kv_caches[0] is not None:
cache_len = kv_caches[0][0].shape[2]
mask = torch.zeros(1, 1, T, cache_len + T, device=x.device)
causal = torch.triu(torch.full((T, T), float("-inf"), device=x.device), diagonal=1)
mask[:, :, :, cache_len:] = causal
else:
mask = None # scaled_dot_product_attention handles causal
new_caches = []
for i, layer in enumerate(self.layers):
cache_i = kv_caches[i] if kv_caches is not None else None
x, new_cache = layer(x, self.rope_freqs, mask, cache_i)
new_caches.append(new_cache)
x = self.norm(x)
logits = self.lm_head(x)
loss = None
if targets is not None:
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1),
ignore_index=self.cfg.TOK_PAD)
return logits, loss, new_caches
def param_count(self): return sum(p.numel() for p in self.parameters())
def param_count_str(self):
n = self.param_count()
return f"{n/1e9:.2f}B" if n >= 1e9 else f"{n/1e6:.1f}M"