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math
|
| 6 |
+
|
| 7 |
+
class RotaryPositionalEmbedding(nn.Module):
|
| 8 |
+
def __init__(self, dim, max_seq_len=2048, base=10000):
|
| 9 |
+
super().__init__()
|
| 10 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
| 11 |
+
self.register_buffer('inv_freq', inv_freq)
|
| 12 |
+
self.max_seq_len = max_seq_len
|
| 13 |
+
|
| 14 |
+
def forward(self, seq_len, device):
|
| 15 |
+
t = torch.arange(seq_len, device=device).type_as(self.inv_freq)
|
| 16 |
+
freqs = torch.einsum('i,j->ij', t, self.inv_freq)
|
| 17 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 18 |
+
return emb.cos(), emb.sin()
|
| 19 |
+
|
| 20 |
+
def apply_rotary_pos_emb(q, k, cos, sin):
|
| 21 |
+
def rotate_half(x):
|
| 22 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 23 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 24 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 25 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 26 |
+
return q_embed, k_embed
|
| 27 |
+
|
| 28 |
+
class MultiHeadSelfAttention(nn.Module):
|
| 29 |
+
def __init__(self, d_model, n_heads, dropout=0.1, max_seq_len=2048):
|
| 30 |
+
super().__init__()
|
| 31 |
+
assert d_model % n_heads == 0
|
| 32 |
+
self.d_model = d_model
|
| 33 |
+
self.n_heads = n_heads
|
| 34 |
+
self.d_k = d_model // n_heads
|
| 35 |
+
self.q_linear = nn.Linear(d_model, d_model, bias=False)
|
| 36 |
+
self.k_linear = nn.Linear(d_model, d_model, bias=False)
|
| 37 |
+
self.v_linear = nn.Linear(d_model, d_model, bias=False)
|
| 38 |
+
self.out_linear = nn.Linear(d_model, d_model, bias=False)
|
| 39 |
+
self.dropout = nn.Dropout(dropout)
|
| 40 |
+
self.attn_dropout = nn.Dropout(dropout)
|
| 41 |
+
self.rope = RotaryPositionalEmbedding(self.d_k, max_seq_len)
|
| 42 |
+
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
|
| 43 |
+
|
| 44 |
+
def forward(self, x, mask=None):
|
| 45 |
+
batch_size, seq_len, d_model = x.size()
|
| 46 |
+
Q = self.q_linear(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
|
| 47 |
+
K = self.k_linear(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
|
| 48 |
+
V = self.v_linear(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
|
| 49 |
+
|
| 50 |
+
cos, sin = self.rope(seq_len, x.device)
|
| 51 |
+
cos = cos[None, None, :, :]
|
| 52 |
+
sin = sin[None, None, :, :]
|
| 53 |
+
Q, K = apply_rotary_pos_emb(Q, K, cos, sin)
|
| 54 |
+
|
| 55 |
+
if self.flash and mask is None:
|
| 56 |
+
context = F.scaled_dot_product_attention(Q, K, V, attn_mask=None, dropout_p=0.0, is_causal=True)
|
| 57 |
+
else:
|
| 58 |
+
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
|
| 59 |
+
if mask is not None:
|
| 60 |
+
scores = scores.masked_fill(mask == 0, float('-inf'))
|
| 61 |
+
attn_weights = F.softmax(scores, dim=-1)
|
| 62 |
+
attn_weights = self.attn_dropout(attn_weights)
|
| 63 |
+
context = torch.matmul(attn_weights, V)
|
| 64 |
+
|
| 65 |
+
context = context.transpose(1, 2).contiguous().view(batch_size, seq_len, d_model)
|
| 66 |
+
output = self.out_linear(context)
|
| 67 |
+
return self.dropout(output)
|
| 68 |
+
|
| 69 |
+
class FeedForward(nn.Module):
|
| 70 |
+
def __init__(self, d_model, d_ff, dropout=0.1):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.linear1 = nn.Linear(d_model, d_ff)
|
| 73 |
+
self.linear2 = nn.Linear(d_ff, d_model)
|
| 74 |
+
self.dropout = nn.Dropout(dropout)
|
| 75 |
+
|
| 76 |
+
def forward(self, x):
|
| 77 |
+
return self.linear2(self.dropout(F.gelu(self.linear1(x))))
|
| 78 |
+
|
| 79 |
+
class RMSNorm(nn.Module):
|
| 80 |
+
def __init__(self, dim, eps=1e-6):
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.eps = eps
|
| 83 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 84 |
+
|
| 85 |
+
def forward(self, x):
|
| 86 |
+
norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 87 |
+
return x * norm * self.weight
|
| 88 |
+
|
| 89 |
+
class TransformerBlock(nn.Module):
|
| 90 |
+
def __init__(self, d_model, n_heads, d_ff, dropout=0.1, max_seq_len=2048, use_swiglu=False):
|
| 91 |
+
super().__init__()
|
| 92 |
+
self.attention = MultiHeadSelfAttention(d_model, n_heads, dropout, max_seq_len)
|
| 93 |
+
self.feed_forward = FeedForward(d_model, d_ff, dropout)
|
| 94 |
+
self.norm1 = RMSNorm(d_model)
|
| 95 |
+
self.norm2 = RMSNorm(d_model)
|
| 96 |
+
self.dropout = nn.Dropout(dropout)
|
| 97 |
+
|
| 98 |
+
def forward(self, x, mask=None):
|
| 99 |
+
x = x + self.attention(self.norm1(x), mask)
|
| 100 |
+
x = x + self.feed_forward(self.norm2(x))
|
| 101 |
+
return x
|
| 102 |
+
|
| 103 |
+
class MTPMiniModel(nn.Module):
|
| 104 |
+
def __init__(self, vocab_size, d_model=512, n_layers=8, n_heads=8,
|
| 105 |
+
d_ff=2048, max_seq_len=512, dropout=0.2, use_swiglu=False):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.vocab_size = vocab_size
|
| 108 |
+
self.d_model = d_model
|
| 109 |
+
self.max_seq_len = max_seq_len
|
| 110 |
+
self.token_embedding = nn.Embedding(vocab_size, d_model)
|
| 111 |
+
self.dropout = nn.Dropout(dropout)
|
| 112 |
+
self.blocks = nn.ModuleList([
|
| 113 |
+
TransformerBlock(d_model, n_heads, d_ff, dropout, max_seq_len, use_swiglu)
|
| 114 |
+
for _ in range(n_layers)
|
| 115 |
+
])
|
| 116 |
+
self.norm_f = RMSNorm(d_model)
|
| 117 |
+
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
|
| 118 |
+
self.lm_head.weight = self.token_embedding.weight
|
| 119 |
+
self.apply(self._init_weights)
|
| 120 |
+
|
| 121 |
+
def _init_weights(self, module):
|
| 122 |
+
if isinstance(module, nn.Linear):
|
| 123 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 124 |
+
if module.bias is not None:
|
| 125 |
+
torch.nn.init.zeros_(module.bias)
|
| 126 |
+
elif isinstance(module, nn.Embedding):
|
| 127 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 128 |
+
|
| 129 |
+
def forward(self, input_ids, targets=None, use_eos_weight=False):
|
| 130 |
+
batch_size, seq_len = input_ids.size()
|
| 131 |
+
mask = torch.tril(torch.ones(seq_len, seq_len, device=input_ids.device)).view(1, 1, seq_len, seq_len)
|
| 132 |
+
x = self.dropout(self.token_embedding(input_ids))
|
| 133 |
+
for block in self.blocks:
|
| 134 |
+
x = block(x, mask)
|
| 135 |
+
x = self.norm_f(x)
|
| 136 |
+
logits = self.lm_head(x)
|
| 137 |
+
|
| 138 |
+
loss = None
|
| 139 |
+
if targets is not None:
|
| 140 |
+
if use_eos_weight:
|
| 141 |
+
weights = torch.ones(self.vocab_size, device=logits.device)
|
| 142 |
+
weights[3] = 2.0
|
| 143 |
+
loss = F.cross_entropy(logits.view(-1, self.vocab_size), targets.view(-1), weight=weights, label_smoothing=0.1)
|
| 144 |
+
else:
|
| 145 |
+
loss = F.cross_entropy(logits.view(-1, self.vocab_size), targets.view(-1), label_smoothing=0.1)
|
| 146 |
+
return logits, loss
|
| 147 |
+
|
| 148 |
+
def count_parameters(self):
|
| 149 |
+
return sum(p.numel() for p in self.parameters() if p.requires_grad)
|