Download modeling_modern_llm.py from devoppro/FastLLM-MoE-seed: direct link, hf CLI and curl.
- Browser
- Download file 5.56 kB
-
https://huggingface.co/devoppro/FastLLM-MoE-seed/resolve/main/modeling_modern_llm.py
- Command line
-
hf download hf://devoppro/FastLLM-MoE-seed/modeling_modern_llm.py
-
curl -L -o modeling_modern_llm.py https://huggingface.co/devoppro/FastLLM-MoE-seed/resolve/main/modeling_modern_llm.py
5.56 kB
| from typing import Optional | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from transformers import PreTrainedModel | |
| from .configuration_modern_llm import ModernLLMConfig | |
| class RMSNorm(nn.Module): | |
| def __init__(self, dim, eps=1e-6): | |
| super().__init__() | |
| self.eps = eps | |
| self.weight = nn.Parameter(torch.ones(dim)) | |
| def forward(self, x): | |
| variance = x.pow(2).mean(-1, keepdim=True) | |
| return x * torch.rsqrt(variance + self.eps) * self.weight | |
| class RotaryEmbedding(nn.Module): | |
| def __init__(self, dim, max_position_embeddings=2048, base=1000000.0): | |
| super().__init__() | |
| inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim)) | |
| self.register_buffer("inv_freq", inv_freq, persistent=False) | |
| def forward(self, x, seq_len): | |
| t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype) | |
| freqs = torch.outer(t, self.inv_freq) | |
| emb = torch.cat((freqs, freqs), dim=-1) | |
| return emb.cos(), emb.sin() | |
| def rotate_half(x): | |
| x1 = x[..., : x.shape[-1] // 2] | |
| x2 = x[..., x.shape[-1] // 2 :] | |
| return torch.cat((-x2, x1), dim=-1) | |
| def apply_rotary_pos_emb(q, k, cos, sin): | |
| cos = cos.unsqueeze(0).unsqueeze(2).to(q.dtype) | |
| sin = sin.unsqueeze(0).unsqueeze(2).to(q.dtype) | |
| return (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin) | |
| class SwiGLU(nn.Module): | |
| def __init__(self, config): | |
| super().__init__() | |
| self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) | |
| self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) | |
| self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False) | |
| def forward(self, x): | |
| return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x)) | |
| class GroupedQueryAttention(nn.Module): | |
| def __init__(self, config): | |
| super().__init__() | |
| self.num_heads = config.num_attention_heads | |
| self.head_dim = config.hidden_size // config.num_attention_heads | |
| self.num_kv_heads = config.num_key_value_heads | |
| self.num_kv_groups = self.num_heads // self.num_kv_heads | |
| self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False) | |
| self.k_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=False) | |
| self.v_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=False) | |
| self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False) | |
| def forward(self, x, rot_cos, rot_sin): | |
| batch_size, seq_len, _ = x.shape | |
| q = self.q_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim) | |
| k = self.k_proj(x).view(batch_size, seq_len, self.num_kv_heads, self.head_dim) | |
| v = self.v_proj(x).view(batch_size, seq_len, self.num_kv_heads, self.head_dim) | |
| q, k = apply_rotary_pos_emb(q, k, rot_cos, rot_sin) | |
| k = k.repeat_interleave(self.num_kv_groups, dim=2) | |
| v = v.repeat_interleave(self.num_kv_groups, dim=2) | |
| q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) | |
| out = F.scaled_dot_product_attention(q, k, v, is_causal=True) | |
| out = out.transpose(1, 2).contiguous().view(batch_size, seq_len, -1) | |
| return self.o_proj(out) | |
| class TransformerBlock(nn.Module): | |
| def __init__(self, config): | |
| super().__init__() | |
| self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) | |
| self.self_attn = GroupedQueryAttention(config) | |
| self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) | |
| self.mlp = SwiGLU(config) | |
| def forward(self, x, rot_cos, rot_sin): | |
| x = x + self.self_attn(self.input_layernorm(x), rot_cos, rot_sin) | |
| x = x + self.mlp(self.post_attention_layernorm(x)) | |
| return x | |
| class ModernLLMForCausalLM(PreTrainedModel): | |
| config_class = ModernLLMConfig | |
| def __init__(self, config): | |
| super().__init__(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.rms_norm_eps) | |
| self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) | |
| self.rotary_emb = RotaryEmbedding(config.hidden_size // config.num_attention_heads, config.max_position_embeddings, config.rope_theta) | |
| self.post_init() | |
| def _init_weights(self, module): | |
| std = 0.02 | |
| if isinstance(module, nn.Linear): | |
| module.weight.data.normal_(mean=0.0, std=std) | |
| if module.bias is not None: | |
| module.bias.data.zero_() | |
| elif isinstance(module, nn.Embedding): | |
| module.weight.data.normal_(mean=0.0, std=std) | |
| def forward(self, input_ids, labels=None, **kwargs): | |
| _, seq_len = input_ids.shape | |
| x = self.embed_tokens(input_ids) | |
| cos, sin = self.rotary_emb(x, seq_len) | |
| for layer in self.layers: | |
| x = layer(x, cos, sin) | |
| x = self.norm(x) | |
| logits = self.lm_head(x) | |
| loss = None | |
| if labels is not None: | |
| shift_logits = logits[..., :-1, :].contiguous() | |
| shift_labels = labels[..., 1:].contiguous() | |
| loss = F.cross_entropy(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1)) | |
| return {"loss": loss, "logits": logits} | |