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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import math
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from config import NexusConfig
|
| 7 |
+
|
| 8 |
+
class RMSNorm(nn.Module):
|
| 9 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.eps = eps
|
| 12 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 13 |
+
|
| 14 |
+
def forward(self, x):
|
| 15 |
+
rms = torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)
|
| 16 |
+
return (x.float() * rms * self.weight.float()).type_as(x)
|
| 17 |
+
|
| 18 |
+
def precompute_freqs_cis(config: NexusConfig) -> torch.Tensor:
|
| 19 |
+
dim = config.dim // config.num_heads
|
| 20 |
+
freqs = 1.0 / (config.rope_theta ** (torch.arange(0, dim, 2).float() / dim))
|
| 21 |
+
t = torch.arange(config.max_seq_len)
|
| 22 |
+
freqs = torch.outer(t, freqs)
|
| 23 |
+
return torch.polar(torch.ones_like(freqs), freqs)
|
| 24 |
+
|
| 25 |
+
class RotaryEmbedding(nn.Module):
|
| 26 |
+
def __init__(self, config: NexusConfig):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.freqs_cis = precompute_freqs_cis(config)
|
| 29 |
+
|
| 30 |
+
def forward(self, x: torch.Tensor, start_pos: int = 0):
|
| 31 |
+
_, seq_len, _, head_dim = x.shape
|
| 32 |
+
freqs_cis = self.freqs_cis[start_pos:start_pos+seq_len, :head_dim//2].to(x.device)
|
| 33 |
+
freqs_cis = freqs_cis.view(1, seq_len, 1, head_dim//2)
|
| 34 |
+
|
| 35 |
+
x_shaped = x.float().reshape(*x.shape[:-1], -1, 2)
|
| 36 |
+
x_complex = torch.complex(x_shaped[..., 0], x_shaped[..., 1])
|
| 37 |
+
|
| 38 |
+
x_rotated = x_complex * freqs_cis
|
| 39 |
+
|
| 40 |
+
x_out = torch.stack([x_rotated.real, x_rotated.imag], dim=-1).reshape_as(x_shaped)
|
| 41 |
+
|
| 42 |
+
return x_out.reshape_as(x).type_as(x)
|
| 43 |
+
|
| 44 |
+
class Attention(nn.Module):
|
| 45 |
+
def __init__(self, config: NexusConfig):
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.num_heads = config.num_heads
|
| 48 |
+
self.num_kv_heads = config.num_kv_heads
|
| 49 |
+
if self.num_kv_heads is None:
|
| 50 |
+
self.num_kv_heads = config.num_heads
|
| 51 |
+
self.head_dim = config.dim // config.num_heads
|
| 52 |
+
self.num_kv_groups = config.num_heads // self.num_kv_heads
|
| 53 |
+
|
| 54 |
+
self.wq = nn.Linear(config.dim, config.dim, bias=False)
|
| 55 |
+
self.wk = nn.Linear(config.dim, self.head_dim * self.num_kv_heads, bias=False)
|
| 56 |
+
self.wv = nn.Linear(config.dim, self.head_dim * self.num_kv_heads, bias=False)
|
| 57 |
+
self.wo = nn.Linear(config.dim, config.dim, bias=False)
|
| 58 |
+
self.rotary = RotaryEmbedding(config)
|
| 59 |
+
|
| 60 |
+
def forward(self, x: torch.Tensor, start_pos: int = 0, mask: Optional[torch.Tensor] = None):
|
| 61 |
+
bsz, seqlen, _ = x.shape
|
| 62 |
+
|
| 63 |
+
q = self.wq(x).view(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2)
|
| 64 |
+
k = self.wk(x).view(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 65 |
+
v = self.wv(x).view(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 66 |
+
|
| 67 |
+
q = self.rotary(q, start_pos)
|
| 68 |
+
k = self.rotary(k, start_pos)
|
| 69 |
+
|
| 70 |
+
if self.num_kv_groups > 1:
|
| 71 |
+
k = k[:, :, None, :, :].expand(bsz, self.num_kv_heads, self.num_kv_groups, seqlen, self.head_dim)
|
| 72 |
+
k = k.reshape(bsz, self.num_heads, seqlen, self.head_dim)
|
| 73 |
+
v = v[:, :, None, :, :].expand(bsz, self.num_kv_heads, self.num_kv_groups, seqlen, self.head_dim)
|
| 74 |
+
v = v.reshape(bsz, self.num_heads, seqlen, self.head_dim)
|
| 75 |
+
|
| 76 |
+
scale = 1.0 / math.sqrt(self.head_dim)
|
| 77 |
+
attn_weights = torch.matmul(q, k.transpose(-2, -1)) * scale
|
| 78 |
+
|
| 79 |
+
if mask is not None:
|
| 80 |
+
attn_weights = attn_weights + mask
|
| 81 |
+
|
| 82 |
+
attn_weights = F.softmax(attn_weights.float(), dim=-1).type_as(q)
|
| 83 |
+
attn_output = torch.matmul(attn_weights, v)
|
| 84 |
+
|
| 85 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
|
| 86 |
+
return self.wo(attn_output)
|
| 87 |
+
|
| 88 |
+
class FeedForward(nn.Module):
|
| 89 |
+
def __init__(self, config: NexusConfig):
|
| 90 |
+
super().__init__()
|
| 91 |
+
hidden_dim = int(2 * config.ff_dim / 3)
|
| 92 |
+
hidden_dim = config.multiple_of * ((hidden_dim + config.multiple_of - 1) // config.multiple_of)
|
| 93 |
+
|
| 94 |
+
self.w1 = nn.Linear(config.dim, hidden_dim, bias=False)
|
| 95 |
+
self.w2 = nn.Linear(hidden_dim, config.dim, bias=False)
|
| 96 |
+
self.w3 = nn.Linear(config.dim, hidden_dim, bias=False)
|
| 97 |
+
|
| 98 |
+
def forward(self, x):
|
| 99 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
| 100 |
+
|
| 101 |
+
class TransformerBlock(nn.Module):
|
| 102 |
+
def __init__(self, config: NexusConfig):
|
| 103 |
+
super().__init__()
|
| 104 |
+
self.attention = Attention(config)
|
| 105 |
+
self.feed_forward = FeedForward(config)
|
| 106 |
+
self.attention_norm = RMSNorm(config.dim, config.norm_eps)
|
| 107 |
+
self.ff_norm = RMSNorm(config.dim, config.norm_eps)
|
| 108 |
+
|
| 109 |
+
def forward(self, x: torch.Tensor, start_pos: int = 0, mask: Optional[torch.Tensor] = None):
|
| 110 |
+
h = x + self.attention(self.attention_norm(x), start_pos, mask)
|
| 111 |
+
out = h + self.feed_forward(self.ff_norm(h))
|
| 112 |
+
return out
|
| 113 |
+
|
| 114 |
+
class Nexus(nn.Module):
|
| 115 |
+
def __init__(self, config: NexusConfig):
|
| 116 |
+
super().__init__()
|
| 117 |
+
self.config = config
|
| 118 |
+
|
| 119 |
+
self.token_embeddings = nn.Embedding(config.vocab_size, config.dim)
|
| 120 |
+
self.layers = nn.ModuleList([TransformerBlock(config) for _ in range(config.num_layers)])
|
| 121 |
+
self.norm = RMSNorm(config.dim, config.norm_eps)
|
| 122 |
+
self.output = nn.Linear(config.dim, config.vocab_size, bias=False)
|
| 123 |
+
|
| 124 |
+
self.token_embeddings.weight = self.output.weight
|
| 125 |
+
|
| 126 |
+
self.apply(self._init_weights)
|
| 127 |
+
|
| 128 |
+
def _init_weights(self, module):
|
| 129 |
+
if isinstance(module, nn.Linear):
|
| 130 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 131 |
+
|
| 132 |
+
def forward(self, input_ids: torch.Tensor, start_pos: int = 0):
|
| 133 |
+
_, seqlen = input_ids.shape
|
| 134 |
+
|
| 135 |
+
mask = torch.full((1, 1, seqlen, start_pos + seqlen), float('-inf'),
|
| 136 |
+
dtype=torch.float32, device=input_ids.device)
|
| 137 |
+
mask = torch.triu(mask, diagonal=start_pos + 1).type_as(input_ids)
|
| 138 |
+
|
| 139 |
+
x = self.token_embeddings(input_ids)
|
| 140 |
+
|
| 141 |
+
for layer in self.layers:
|
| 142 |
+
x = layer(x, start_pos, mask)
|
| 143 |
+
|
| 144 |
+
x = self.norm(x)
|
| 145 |
+
logits = self.output(x)
|
| 146 |
+
|
| 147 |
+
return logits
|
| 148 |
+
|
| 149 |
+
def generate(self, input_ids: torch.Tensor, max_new_tokens: int,
|
| 150 |
+
temperature: float = 0.7, top_k: int = 50, top_p: float = 0.9):
|
| 151 |
+
self.eval()
|
| 152 |
+
generated = []
|
| 153 |
+
|
| 154 |
+
for _ in range(max_new_tokens):
|
| 155 |
+
seq_len = input_ids.shape[1]
|
| 156 |
+
if seq_len > self.config.max_seq_len:
|
| 157 |
+
input_ids = input_ids[:, -self.config.max_seq_len:]
|
| 158 |
+
|
| 159 |
+
with torch.no_grad():
|
| 160 |
+
logits = self(input_ids, 0)
|
| 161 |
+
logits = logits[:, -1, :] / temperature
|
| 162 |
+
|
| 163 |
+
if top_k > 0:
|
| 164 |
+
top_k_values, _ = torch.topk(logits, top_k)
|
| 165 |
+
min_top_k = top_k_values[:, -1].unsqueeze(-1)
|
| 166 |
+
logits = torch.where(logits < min_top_k,
|
| 167 |
+
torch.full_like(logits, float('-inf')), logits)
|
| 168 |
+
|
| 169 |
+
if top_p > 0:
|
| 170 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 171 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 172 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 173 |
+
sorted_indices_to_remove[:, 0] = False
|
| 174 |
+
indices_to_remove = torch.zeros_like(logits, dtype=torch.bool)
|
| 175 |
+
indices_to_remove = indices_to_remove.scatter(1, sorted_indices,
|
| 176 |
+
sorted_indices_to_remove)
|
| 177 |
+
logits = torch.where(indices_to_remove,
|
| 178 |
+
torch.full_like(logits, float('-inf')), logits)
|
| 179 |
+
|
| 180 |
+
probs = F.softmax(logits, dim=-1)
|
| 181 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 182 |
+
|
| 183 |
+
input_ids = torch.cat([input_ids, next_token], dim=-1)
|
| 184 |
+
generated.append(next_token.item())
|
| 185 |
+
|
| 186 |
+
return generated, input_ids
|
| 187 |
+
|
| 188 |
+
def create_nexus_model():
|
| 189 |
+
from config import nexus_config
|
| 190 |
+
config = nexus_config
|
| 191 |
+
|
| 192 |
+
model = Nexus(config)
|
| 193 |
+
total_params = sum(p.numel() for p in model.parameters())
|
| 194 |
+
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 195 |
+
|
| 196 |
+
print(f"[Nexus SmAll] Model created with {total_params/1e6:.1f}M parameters "
|
| 197 |
+
f"({trainable_params/1e6:.1f}M trainable)")
|
| 198 |
+
|
| 199 |
+
return model, config
|