Upload modeling_modern_llm.py with huggingface_hub
Browse files- modeling_modern_llm.py +123 -0
modeling_modern_llm.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from transformers import PreTrainedModel
|
| 7 |
+
|
| 8 |
+
from .configuration_modern_llm import ModernLLMConfig
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class RMSNorm(nn.Module):
|
| 12 |
+
def __init__(self, dim, eps=1e-6):
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.eps = eps
|
| 15 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 16 |
+
|
| 17 |
+
def forward(self, x):
|
| 18 |
+
variance = x.pow(2).mean(-1, keepdim=True)
|
| 19 |
+
return x * torch.rsqrt(variance + self.eps) * self.weight
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class RotaryEmbedding(nn.Module):
|
| 23 |
+
def __init__(self, dim, max_position_embeddings=2048, base=1000000.0):
|
| 24 |
+
super().__init__()
|
| 25 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
| 26 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 27 |
+
|
| 28 |
+
def forward(self, x, seq_len):
|
| 29 |
+
t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
|
| 30 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 31 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 32 |
+
return emb.cos(), emb.sin()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def rotate_half(x):
|
| 36 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 37 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 38 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def apply_rotary_pos_emb(q, k, cos, sin):
|
| 42 |
+
cos = cos.unsqueeze(0).unsqueeze(2).to(q.dtype)
|
| 43 |
+
sin = sin.unsqueeze(0).unsqueeze(2).to(q.dtype)
|
| 44 |
+
return (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class SwiGLU(nn.Module):
|
| 48 |
+
def __init__(self, config):
|
| 49 |
+
super().__init__()
|
| 50 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 51 |
+
self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 52 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 53 |
+
|
| 54 |
+
def forward(self, x):
|
| 55 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class GroupedQueryAttention(nn.Module):
|
| 59 |
+
def __init__(self, config):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.num_heads = config.num_attention_heads
|
| 62 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
| 63 |
+
self.num_kv_heads = config.num_key_value_heads
|
| 64 |
+
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 65 |
+
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 66 |
+
self.k_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
|
| 67 |
+
self.v_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
|
| 68 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
|
| 69 |
+
|
| 70 |
+
def forward(self, x, rot_cos, rot_sin):
|
| 71 |
+
batch_size, seq_len, _ = x.shape
|
| 72 |
+
q = self.q_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim)
|
| 73 |
+
k = self.k_proj(x).view(batch_size, seq_len, self.num_kv_heads, self.head_dim)
|
| 74 |
+
v = self.v_proj(x).view(batch_size, seq_len, self.num_kv_heads, self.head_dim)
|
| 75 |
+
q, k = apply_rotary_pos_emb(q, k, rot_cos, rot_sin)
|
| 76 |
+
k = k.repeat_interleave(self.num_kv_groups, dim=2)
|
| 77 |
+
v = v.repeat_interleave(self.num_kv_groups, dim=2)
|
| 78 |
+
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
|
| 79 |
+
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 80 |
+
out = out.transpose(1, 2).contiguous().view(batch_size, seq_len, -1)
|
| 81 |
+
return self.o_proj(out)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class TransformerBlock(nn.Module):
|
| 85 |
+
def __init__(self, config):
|
| 86 |
+
super().__init__()
|
| 87 |
+
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 88 |
+
self.self_attn = GroupedQueryAttention(config)
|
| 89 |
+
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 90 |
+
self.mlp = SwiGLU(config)
|
| 91 |
+
|
| 92 |
+
def forward(self, x, rot_cos, rot_sin):
|
| 93 |
+
x = x + self.self_attn(self.input_layernorm(x), rot_cos, rot_sin)
|
| 94 |
+
x = x + self.mlp(self.post_attention_layernorm(x))
|
| 95 |
+
return x
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class ModernLLMForCausalLM(PreTrainedModel):
|
| 99 |
+
config_class = ModernLLMConfig
|
| 100 |
+
|
| 101 |
+
def __init__(self, config):
|
| 102 |
+
super().__init__(config)
|
| 103 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 104 |
+
self.layers = nn.ModuleList([TransformerBlock(config) for _ in range(config.num_hidden_layers)])
|
| 105 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 106 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 107 |
+
self.rotary_emb = RotaryEmbedding(config.hidden_size // config.num_attention_heads, config.max_position_embeddings, config.rope_theta)
|
| 108 |
+
self.post_init()
|
| 109 |
+
|
| 110 |
+
def forward(self, input_ids, labels=None, **kwargs):
|
| 111 |
+
_, seq_len = input_ids.shape
|
| 112 |
+
x = self.embed_tokens(input_ids)
|
| 113 |
+
cos, sin = self.rotary_emb(x, seq_len)
|
| 114 |
+
for layer in self.layers:
|
| 115 |
+
x = layer(x, cos, sin)
|
| 116 |
+
x = self.norm(x)
|
| 117 |
+
logits = self.lm_head(x)
|
| 118 |
+
loss = None
|
| 119 |
+
if labels is not None:
|
| 120 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 121 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 122 |
+
loss = F.cross_entropy(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
|
| 123 |
+
return {"loss": loss, "logits": logits}
|