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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Optional, Tuple
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class MarsLMConfig:
|
| 12 |
+
vocab_size: int = 32000
|
| 13 |
+
hidden_size: int = 768
|
| 14 |
+
intermediate_size: int = 2048
|
| 15 |
+
num_hidden_layers: int = 12
|
| 16 |
+
num_attention_heads: int = 12
|
| 17 |
+
max_position_embeddings: int = 2048
|
| 18 |
+
dropout: float = 0.0
|
| 19 |
+
layer_norm_eps: float = 1e-5
|
| 20 |
+
rope_theta: float = 10000.0
|
| 21 |
+
use_cache: bool = True
|
| 22 |
+
|
| 23 |
+
@property
|
| 24 |
+
def head_dim(self) -> int:
|
| 25 |
+
return self.hidden_size // self.num_attention_heads
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class RMSNorm(nn.Module):
|
| 29 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.eps = eps
|
| 32 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 33 |
+
|
| 34 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 35 |
+
rms = x.pow(2).mean(-1, keepdim=True).add(self.eps).sqrt()
|
| 36 |
+
return self.weight * (x / rms)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _build_rotary_cache(positions: torch.Tensor, head_dim: int, theta: float, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 40 |
+
if head_dim % 2 != 0:
|
| 41 |
+
raise ValueError("head_dim must be even for rotary embeddings")
|
| 42 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim))
|
| 43 |
+
freqs = torch.einsum("bt,d->btd", positions.to(torch.float32), inv_freq)
|
| 44 |
+
cos = torch.cos(freqs)
|
| 45 |
+
sin = torch.sin(freqs)
|
| 46 |
+
return cos, sin
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 50 |
+
x = x.to(torch.float32)
|
| 51 |
+
x_even = x[..., 0::2]
|
| 52 |
+
x_odd = x[..., 1::2]
|
| 53 |
+
x_pairs = torch.stack((x_even, x_odd), dim=-1)
|
| 54 |
+
rotated = torch.stack((-x_pairs[..., 1], x_pairs[..., 0]), dim=-1)
|
| 55 |
+
cos = cos.unsqueeze(-1)
|
| 56 |
+
sin = sin.unsqueeze(-1)
|
| 57 |
+
out = x_pairs * cos + rotated * sin
|
| 58 |
+
return out.flatten(-2).to(dtype=x.dtype)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class CausalSelfAttention(nn.Module):
|
| 62 |
+
def __init__(self, config: MarsLMConfig):
|
| 63 |
+
super().__init__()
|
| 64 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 65 |
+
raise ValueError("hidden_size must be divisible by num_attention_heads")
|
| 66 |
+
self.config = config
|
| 67 |
+
self.num_heads = config.num_attention_heads
|
| 68 |
+
self.head_dim = config.head_dim
|
| 69 |
+
self.q_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 70 |
+
self.k_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 71 |
+
self.v_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 72 |
+
self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 73 |
+
self.attn_dropout = nn.Dropout(config.dropout)
|
| 74 |
+
self.resid_dropout = nn.Dropout(config.dropout)
|
| 75 |
+
|
| 76 |
+
def _build_causal_mask(self, q_len: int, kv_len: int, device: torch.device) -> Optional[torch.Tensor]:
|
| 77 |
+
if q_len == 1 and kv_len == 1:
|
| 78 |
+
return None
|
| 79 |
+
mask = torch.ones((1, 1, q_len, kv_len), device=device, dtype=torch.bool)
|
| 80 |
+
for qi in range(q_len):
|
| 81 |
+
mask[:, :, qi, qi + 1:] = False
|
| 82 |
+
return mask
|
| 83 |
+
|
| 84 |
+
def forward(
|
| 85 |
+
self,
|
| 86 |
+
x: torch.Tensor,
|
| 87 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 88 |
+
past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 89 |
+
use_cache: bool = False,
|
| 90 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 91 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
| 92 |
+
batch_size, seq_len, _ = x.size()
|
| 93 |
+
q = self.q_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 94 |
+
k = self.k_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 95 |
+
v = self.v_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 96 |
+
|
| 97 |
+
if position_ids is None:
|
| 98 |
+
position_ids = torch.arange(seq_len, device=x.device).unsqueeze(0).expand(batch_size, -1)
|
| 99 |
+
cos, sin = _build_rotary_cache(position_ids, self.head_dim, self.config.rope_theta, x.device)
|
| 100 |
+
cos = cos.unsqueeze(1)
|
| 101 |
+
sin = sin.unsqueeze(1)
|
| 102 |
+
q = _apply_rotary(q, cos, sin)
|
| 103 |
+
k = _apply_rotary(k, cos, sin)
|
| 104 |
+
|
| 105 |
+
if past_key_value is not None:
|
| 106 |
+
prev_k, prev_v = past_key_value
|
| 107 |
+
k = torch.cat([prev_k, k], dim=2)
|
| 108 |
+
v = torch.cat([prev_v, v], dim=2)
|
| 109 |
+
present_key_value = (k, v) if use_cache else None
|
| 110 |
+
|
| 111 |
+
if attention_mask is not None:
|
| 112 |
+
attn_mask = attention_mask.to(dtype=torch.bool, device=x.device)
|
| 113 |
+
if attn_mask.dim() == 2:
|
| 114 |
+
attn_mask = attn_mask[:, None, None, :]
|
| 115 |
+
else:
|
| 116 |
+
attn_mask = self._build_causal_mask(seq_len, k.size(2), x.device)
|
| 117 |
+
|
| 118 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 119 |
+
if attn_mask is not None:
|
| 120 |
+
scores = scores.masked_fill(~attn_mask, torch.finfo(scores.dtype).min)
|
| 121 |
+
probs = torch.softmax(scores, dim=-1)
|
| 122 |
+
attn_output = torch.matmul(probs, v)
|
| 123 |
+
|
| 124 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.config.hidden_size)
|
| 125 |
+
attn_output = self.o_proj(attn_output)
|
| 126 |
+
attn_output = self.resid_dropout(attn_output)
|
| 127 |
+
return attn_output, present_key_value
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class MLP(nn.Module):
|
| 131 |
+
def __init__(self, config: MarsLMConfig):
|
| 132 |
+
super().__init__()
|
| 133 |
+
self.c_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 134 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 135 |
+
self.out_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 136 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 137 |
+
|
| 138 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 139 |
+
hidden = F.silu(self.c_proj(x)) * self.gate_proj(x)
|
| 140 |
+
hidden = self.out_proj(hidden)
|
| 141 |
+
return self.dropout(hidden)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class TransformerBlock(nn.Module):
|
| 145 |
+
def __init__(self, config: MarsLMConfig):
|
| 146 |
+
super().__init__()
|
| 147 |
+
self.attn_norm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 148 |
+
self.ffn_norm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 149 |
+
self.attn = CausalSelfAttention(config)
|
| 150 |
+
self.mlp = MLP(config)
|
| 151 |
+
|
| 152 |
+
def forward(
|
| 153 |
+
self,
|
| 154 |
+
x: torch.Tensor,
|
| 155 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 156 |
+
past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 157 |
+
use_cache: bool = False,
|
| 158 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 159 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
| 160 |
+
attn_input = self.attn_norm(x)
|
| 161 |
+
attn_output, present = self.attn(attn_input, attention_mask, past_key_value, use_cache, position_ids)
|
| 162 |
+
x = x + attn_output
|
| 163 |
+
ffn_input = self.ffn_norm(x)
|
| 164 |
+
x = x + self.mlp(ffn_input)
|
| 165 |
+
return x, present
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class MarsLMModel(nn.Module):
|
| 169 |
+
def __init__(self, config: MarsLMConfig):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.config = config
|
| 172 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 173 |
+
self.layers = nn.ModuleList([TransformerBlock(config) for _ in range(config.num_hidden_layers)])
|
| 174 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 175 |
+
|
| 176 |
+
def forward(
|
| 177 |
+
self,
|
| 178 |
+
input_ids: torch.Tensor,
|
| 179 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 180 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
| 181 |
+
use_cache: bool = False,
|
| 182 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 183 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]]]:
|
| 184 |
+
hidden_states = self.embed_tokens(input_ids)
|
| 185 |
+
present = [] if use_cache else None
|
| 186 |
+
if past_key_values is None:
|
| 187 |
+
past_key_values = [None] * len(self.layers)
|
| 188 |
+
for idx, layer in enumerate(self.layers):
|
| 189 |
+
hidden_states, layer_present = layer(
|
| 190 |
+
hidden_states,
|
| 191 |
+
attention_mask,
|
| 192 |
+
past_key_values[idx],
|
| 193 |
+
use_cache=use_cache,
|
| 194 |
+
position_ids=position_ids,
|
| 195 |
+
)
|
| 196 |
+
if use_cache:
|
| 197 |
+
present.append(layer_present)
|
| 198 |
+
hidden_states = self.norm(hidden_states)
|
| 199 |
+
return hidden_states, tuple(present) if use_cache else None
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class MarsLMForCausalLM(nn.Module):
|
| 203 |
+
def __init__(self, config: MarsLMConfig):
|
| 204 |
+
super().__init__()
|
| 205 |
+
self.config = config
|
| 206 |
+
self.model = MarsLMModel(config)
|
| 207 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 208 |
+
|
| 209 |
+
def forward(
|
| 210 |
+
self,
|
| 211 |
+
input_ids: torch.Tensor,
|
| 212 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 213 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
| 214 |
+
use_cache: bool = False,
|
| 215 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 216 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]]]:
|
| 217 |
+
hidden_states, present = self.model(
|
| 218 |
+
input_ids=input_ids,
|
| 219 |
+
attention_mask=attention_mask,
|
| 220 |
+
past_key_values=past_key_values,
|
| 221 |
+
use_cache=use_cache,
|
| 222 |
+
position_ids=position_ids,
|
| 223 |
+
)
|
| 224 |
+
logits = self.lm_head(hidden_states)
|
| 225 |
+
return logits, present
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def build_model_from_config(config: MarsLMConfig) -> MarsLMForCausalLM:
|
| 229 |
+
return MarsLMForCausalLM(config)
|