import torch import torch.nn as nn import torch.nn.functional as F from .config import ModelConfig class RMSNorm(nn.Module): def __init__(self, hidden_size: int, eps: float): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.eps = eps def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: variance = hidden_states.float().pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.eps).to(hidden_states.dtype) return hidden_states * self.weight.to(hidden_states.dtype) class RotaryEmbedding(nn.Module): def __init__(self, dim: int, theta: float): super().__init__() inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) def forward(self, position_ids: torch.Tensor, dtype: torch.dtype): freqs = position_ids.float().unsqueeze(-1) * self.inv_freq.unsqueeze(0) emb = torch.cat((freqs, freqs), dim=-1) return emb.cos().to(dtype), emb.sin().to(dtype) def rotate_half(x: torch.Tensor) -> torch.Tensor: x1, x2 = x.chunk(2, dim=-1) return torch.cat((-x2, x1), dim=-1) def apply_rope(q, k, cos, sin): cos = cos.unsqueeze(0).unsqueeze(0) sin = sin.unsqueeze(0).unsqueeze(0) return q * cos + rotate_half(q) * sin, k * cos + rotate_half(k) * sin def repeat_kv(x: torch.Tensor, repeats: int) -> torch.Tensor: if repeats == 1: return x b, kv_heads, t, d = x.shape return ( x[:, :, None, :, :] .expand(b, kv_heads, repeats, t, d) .reshape(b, kv_heads * repeats, t, d) ) class CausalSelfAttention(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() self.num_heads = cfg.num_attention_heads self.num_kv_heads = cfg.num_key_value_heads self.head_dim = cfg.head_dim self.kv_repeats = self.num_heads // self.num_kv_heads self.dropout = cfg.dropout kv_dim = self.num_kv_heads * self.head_dim self.q_proj = nn.Linear(cfg.hidden_size, self.num_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(cfg.hidden_size, kv_dim, bias=False) self.v_proj = nn.Linear(cfg.hidden_size, kv_dim, bias=False) self.o_proj = nn.Linear(cfg.hidden_size, cfg.hidden_size, bias=False) def forward(self, hidden_states, cos, sin, segment_ids=None, past_key_value=None, use_cache=False): b, t, _ = hidden_states.shape q = self.q_proj(hidden_states).view(b, t, self.num_heads, self.head_dim).transpose(1, 2) k = self.k_proj(hidden_states).view(b, t, self.num_kv_heads, self.head_dim).transpose(1, 2) v = self.v_proj(hidden_states).view(b, t, self.num_kv_heads, self.head_dim).transpose(1, 2) q, k = apply_rope(q, k, cos, sin) had_past = past_key_value is not None if had_past: past_k, past_v = past_key_value k = torch.cat((past_k, k), dim=2) v = torch.cat((past_v, v), dim=2) present = (k, v) if use_cache else None k_attn = repeat_kv(k, self.kv_repeats) v_attn = repeat_kv(v, self.kv_repeats) attn_mask = None is_causal = not had_past if segment_ids is not None: if had_past: raise ValueError("segment_ids are not supported with KV cache") same_doc = segment_ids[:, None, :, None] == segment_ids[:, None, None, :] causal = torch.ones((t, t), device=hidden_states.device, dtype=torch.bool).tril() attn_mask = same_doc & causal[None, None, :, :] is_causal = False out = F.scaled_dot_product_attention( q, k_attn, v_attn, attn_mask=attn_mask, dropout_p=self.dropout if self.training else 0.0, is_causal=is_causal, ) out = out.transpose(1, 2).contiguous().view(b, t, -1) return self.o_proj(out), present class SwiGLU(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() self.gate_proj = nn.Linear(cfg.hidden_size, cfg.intermediate_size, bias=False) self.up_proj = nn.Linear(cfg.hidden_size, cfg.intermediate_size, bias=False) self.down_proj = nn.Linear(cfg.intermediate_size, cfg.hidden_size, bias=False) def forward(self, x): return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x)) class DecoderLayer(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() self.self_attn = CausalSelfAttention(cfg) self.mlp = SwiGLU(cfg) self.input_layernorm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps) self.post_attention_layernorm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps) def forward(self, x, cos, sin, segment_ids=None, past_key_value=None, use_cache=False): attn_out, present = self.self_attn( self.input_layernorm(x), cos, sin, segment_ids=segment_ids, past_key_value=past_key_value, use_cache=use_cache, ) x = x + attn_out x = x + self.mlp(self.post_attention_layernorm(x)) return x, present