Buckets:
| import math | |
| from dataclasses import dataclass | |
| from typing import Optional, Tuple | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| class MarsLMConfig: | |
| vocab_size: int = 32000 | |
| hidden_size: int = 768 | |
| intermediate_size: int = 2048 | |
| num_hidden_layers: int = 12 | |
| num_attention_heads: int = 12 | |
| max_position_embeddings: int = 2048 | |
| dropout: float = 0.0 | |
| layer_norm_eps: float = 1e-5 | |
| rope_theta: float = 10000.0 | |
| use_cache: bool = True | |
| def head_dim(self) -> int: | |
| return self.hidden_size // self.num_attention_heads | |
| class RMSNorm(nn.Module): | |
| def __init__(self, dim: int, eps: float = 1e-5): | |
| super().__init__() | |
| self.eps = eps | |
| self.weight = nn.Parameter(torch.ones(dim)) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| rms = x.pow(2).mean(-1, keepdim=True).add(self.eps).sqrt() | |
| return self.weight * (x / rms) | |
| def _build_rotary_cache(positions: torch.Tensor, head_dim: int, theta: float, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]: | |
| if head_dim % 2 != 0: | |
| raise ValueError("head_dim must be even for rotary embeddings") | |
| inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim)) | |
| freqs = torch.einsum("bt,d->btd", positions.to(torch.float32), inv_freq) | |
| cos = torch.cos(freqs) | |
| sin = torch.sin(freqs) | |
| return cos, sin | |
| def _apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: | |
| x = x.to(torch.float32) | |
| x_even = x[..., 0::2] | |
| x_odd = x[..., 1::2] | |
| x_pairs = torch.stack((x_even, x_odd), dim=-1) | |
| rotated = torch.stack((-x_pairs[..., 1], x_pairs[..., 0]), dim=-1) | |
| cos = cos.unsqueeze(-1) | |
| sin = sin.unsqueeze(-1) | |
| out = x_pairs * cos + rotated * sin | |
| return out.flatten(-2).to(dtype=x.dtype) | |
| class CausalSelfAttention(nn.Module): | |
| def __init__(self, config: MarsLMConfig): | |
| super().__init__() | |
| if config.hidden_size % config.num_attention_heads != 0: | |
| raise ValueError("hidden_size must be divisible by num_attention_heads") | |
| self.config = config | |
| self.num_heads = config.num_attention_heads | |
| self.head_dim = config.head_dim | |
| self.q_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False) | |
| self.k_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False) | |
| self.v_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False) | |
| self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False) | |
| self.attn_dropout = nn.Dropout(config.dropout) | |
| self.resid_dropout = nn.Dropout(config.dropout) | |
| def _build_causal_mask(self, q_len: int, kv_len: int, device: torch.device) -> Optional[torch.Tensor]: | |
| if q_len == 1 and kv_len == 1: | |
| return None | |
| mask = torch.ones((1, 1, q_len, kv_len), device=device, dtype=torch.bool) | |
| for qi in range(q_len): | |
| mask[:, :, qi, qi + 1:] = False | |
| return mask | |
| def forward( | |
| self, | |
| x: torch.Tensor, | |
| attention_mask: Optional[torch.Tensor] = None, | |
| past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, | |
| use_cache: bool = False, | |
| position_ids: Optional[torch.Tensor] = None, | |
| ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: | |
| batch_size, seq_len, _ = x.size() | |
| q = self.q_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2) | |
| k = self.k_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2) | |
| v = self.v_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2) | |
| if position_ids is None: | |
| position_ids = torch.arange(seq_len, device=x.device).unsqueeze(0).expand(batch_size, -1) | |
| cos, sin = _build_rotary_cache(position_ids, self.head_dim, self.config.rope_theta, x.device) | |
| cos = cos.unsqueeze(1) | |
| sin = sin.unsqueeze(1) | |
| q = _apply_rotary(q, cos, sin) | |
| k = _apply_rotary(k, cos, sin) | |
| if past_key_value is not None: | |
| prev_k, prev_v = past_key_value | |
| k = torch.cat([prev_k, k], dim=2) | |
| v = torch.cat([prev_v, v], dim=2) | |
| present_key_value = (k, v) if use_cache else None | |
| if attention_mask is not None: | |
| attn_mask = attention_mask.to(dtype=torch.bool, device=x.device) | |
| if attn_mask.dim() == 2: | |
| attn_mask = attn_mask[:, None, None, :] | |
| else: | |
| attn_mask = self._build_causal_mask(seq_len, k.size(2), x.device) | |
| scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim) | |
| if attn_mask is not None: | |
| scores = scores.masked_fill(~attn_mask, torch.finfo(scores.dtype).min) | |
| probs = torch.softmax(scores, dim=-1) | |
| attn_output = torch.matmul(probs, v) | |
| attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.config.hidden_size) | |
| attn_output = self.o_proj(attn_output) | |
| attn_output = self.resid_dropout(attn_output) | |
| return attn_output, present_key_value | |
| class MLP(nn.Module): | |
| def __init__(self, config: MarsLMConfig): | |
| super().__init__() | |
| self.c_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) | |
| self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) | |
| self.out_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False) | |
| self.dropout = nn.Dropout(config.dropout) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| hidden = F.silu(self.c_proj(x)) * self.gate_proj(x) | |
| hidden = self.out_proj(hidden) | |
| return self.dropout(hidden) | |
| class TransformerBlock(nn.Module): | |
| def __init__(self, config: MarsLMConfig): | |
| super().__init__() | |
| self.attn_norm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps) | |
| self.ffn_norm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps) | |
| self.attn = CausalSelfAttention(config) | |
| self.mlp = MLP(config) | |
| def forward( | |
| self, | |
| x: torch.Tensor, | |
| attention_mask: Optional[torch.Tensor] = None, | |
| past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, | |
| use_cache: bool = False, | |
| position_ids: Optional[torch.Tensor] = None, | |
| ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: | |
| attn_input = self.attn_norm(x) | |
| attn_output, present = self.attn(attn_input, attention_mask, past_key_value, use_cache, position_ids) | |
| x = x + attn_output | |
| ffn_input = self.ffn_norm(x) | |
| x = x + self.mlp(ffn_input) | |
| return x, present | |
| class MarsLMModel(nn.Module): | |
| def __init__(self, config: MarsLMConfig): | |
| super().__init__() | |
| self.config = config | |
| self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) | |
| self.layers = nn.ModuleList([TransformerBlock(config) for _ in range(config.num_hidden_layers)]) | |
| self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps) | |
| def forward( | |
| self, | |
| input_ids: torch.Tensor, | |
| attention_mask: Optional[torch.Tensor] = None, | |
| past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None, | |
| use_cache: bool = False, | |
| position_ids: Optional[torch.Tensor] = None, | |
| ) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]]]: | |
| hidden_states = self.embed_tokens(input_ids) | |
| present = [] if use_cache else None | |
| if past_key_values is None: | |
| past_key_values = [None] * len(self.layers) | |
| for idx, layer in enumerate(self.layers): | |
| hidden_states, layer_present = layer( | |
| hidden_states, | |
| attention_mask, | |
| past_key_values[idx], | |
| use_cache=use_cache, | |
| position_ids=position_ids, | |
| ) | |
| if use_cache: | |
| present.append(layer_present) | |
| hidden_states = self.norm(hidden_states) | |
| return hidden_states, tuple(present) if use_cache else None | |
| class MarsLMForCausalLM(nn.Module): | |
| def __init__(self, config: MarsLMConfig): | |
| super().__init__() | |
| self.config = config | |
| self.model = MarsLMModel(config) | |
| self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) | |
| def forward( | |
| self, | |
| input_ids: torch.Tensor, | |
| attention_mask: Optional[torch.Tensor] = None, | |
| past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None, | |
| use_cache: bool = False, | |
| position_ids: Optional[torch.Tensor] = None, | |
| ) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]]]: | |
| hidden_states, present = self.model( | |
| input_ids=input_ids, | |
| attention_mask=attention_mask, | |
| past_key_values=past_key_values, | |
| use_cache=use_cache, | |
| position_ids=position_ids, | |
| ) | |
| logits = self.lm_head(hidden_states) | |
| return logits, present | |
| def build_model_from_config(config: MarsLMConfig) -> MarsLMForCausalLM: | |
| return MarsLMForCausalLM(config) | |
Xet Storage Details
- Size:
- 9.33 kB
- Xet hash:
- b277e990ce45684968b2f010bf1d6d1720764582c67284845098a148f0c1c21d
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.