JustScriptzz commited on
Commit
b702163
·
verified ·
1 Parent(s): a936da0

Upload modeling_nexus_small.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_nexus_small.py +287 -0
modeling_nexus_small.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from transformers import PreTrainedModel, PretrainedConfig, AutoConfig, AutoModel
8
+
9
+ try:
10
+ from config import NexusConfig
11
+ except ImportError:
12
+ from .config import NexusConfig
13
+
14
+
15
+ class NexusConfigHF(PretrainedConfig):
16
+ model_type = "nexus_small"
17
+
18
+ def __init__(
19
+ self,
20
+ vocab_size=50304,
21
+ max_seq_len=512,
22
+ dim=768,
23
+ num_layers=10,
24
+ num_heads=12,
25
+ num_kv_heads=4,
26
+ multiple_of=256,
27
+ ff_dim=2048,
28
+ norm_eps=1e-6,
29
+ rope_theta=500000.0,
30
+ **kwargs,
31
+ ):
32
+ super().__init__(**kwargs)
33
+ self.vocab_size = vocab_size
34
+ self.max_seq_len = max_seq_len
35
+ self.dim = dim
36
+ self.num_layers = num_layers
37
+ self.num_heads = num_heads
38
+ self.num_kv_heads = num_kv_heads
39
+ self.multiple_of = multiple_of
40
+ self.ff_dim = ff_dim
41
+ self.norm_eps = norm_eps
42
+ self.rope_theta = rope_theta
43
+
44
+ class RMSNorm(nn.Module):
45
+ def __init__(self, dim: int, eps: float = 1e-6):
46
+ super().__init__()
47
+ self.eps = eps
48
+ self.weight = nn.Parameter(torch.ones(dim))
49
+
50
+ def forward(self, x):
51
+ rms = torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)
52
+ return (x.float() * rms * self.weight.float()).type_as(x)
53
+
54
+ def precompute_freqs_cis(config: NexusConfig) -> torch.Tensor:
55
+ dim = config.dim // config.num_heads
56
+ freqs = 1.0 / (config.rope_theta ** (torch.arange(0, dim, 2).float() / dim))
57
+ t = torch.arange(config.max_seq_len)
58
+ freqs = torch.outer(t, freqs)
59
+ return torch.polar(torch.ones_like(freqs), freqs)
60
+
61
+ class RotaryEmbedding(nn.Module):
62
+ def __init__(self, config: NexusConfig):
63
+ super().__init__()
64
+ self.freqs_cis = precompute_freqs_cis(config)
65
+
66
+ def forward(self, x: torch.Tensor, start_pos: int = 0):
67
+ _, seq_len, _, head_dim = x.shape
68
+ freqs_cis = self.freqs_cis[start_pos:start_pos+seq_len, :head_dim//2].to(x.device)
69
+ freqs_cis = freqs_cis.view(1, seq_len, 1, head_dim//2)
70
+
71
+ x_shaped = x.float().reshape(*x.shape[:-1], -1, 2)
72
+ x_complex = torch.complex(x_shaped[..., 0], x_shaped[..., 1])
73
+
74
+ x_rotated = x_complex * freqs_cis
75
+
76
+ x_out = torch.stack([x_rotated.real, x_rotated.imag], dim=-1).reshape_as(x_shaped)
77
+
78
+ return x_out.reshape_as(x).type_as(x)
79
+
80
+ class Attention(nn.Module):
81
+ def __init__(self, config: NexusConfig):
82
+ super().__init__()
83
+ self.num_heads = config.num_heads
84
+ self.num_kv_heads = config.num_kv_heads
85
+ if self.num_kv_heads is None:
86
+ self.num_kv_heads = config.num_heads
87
+ self.head_dim = config.dim // config.num_heads
88
+ self.num_kv_groups = config.num_heads // self.num_kv_heads
89
+
90
+ self.wq = nn.Linear(config.dim, config.dim, bias=False)
91
+ self.wk = nn.Linear(config.dim, self.head_dim * self.num_kv_heads, bias=False)
92
+ self.wv = nn.Linear(config.dim, self.head_dim * self.num_kv_heads, bias=False)
93
+ self.wo = nn.Linear(config.dim, config.dim, bias=False)
94
+ self.rotary = RotaryEmbedding(config)
95
+
96
+ def forward(self, x: torch.Tensor, start_pos: int = 0, mask: Optional[torch.Tensor] = None):
97
+ bsz, seqlen, _ = x.shape
98
+
99
+ q = self.wq(x).view(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2)
100
+ k = self.wk(x).view(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)
101
+ v = self.wv(x).view(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)
102
+
103
+ q = self.rotary(q, start_pos)
104
+ k = self.rotary(k, start_pos)
105
+
106
+ if self.num_kv_groups > 1:
107
+ k = k[:, :, None, :, :].expand(bsz, self.num_kv_heads, self.num_kv_groups, seqlen, self.head_dim)
108
+ k = k.reshape(bsz, self.num_heads, seqlen, self.head_dim)
109
+ v = v[:, :, None, :, :].expand(bsz, self.num_kv_heads, self.num_kv_groups, seqlen, self.head_dim)
110
+ v = v.reshape(bsz, self.num_heads, seqlen, self.head_dim)
111
+
112
+ scale = 1.0 / math.sqrt(self.head_dim)
113
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) * scale
114
+
115
+ if mask is not None:
116
+ attn_weights = attn_weights + mask
117
+
118
+ attn_weights = F.softmax(attn_weights.float(), dim=-1).type_as(q)
119
+ attn_output = torch.matmul(attn_weights, v)
120
+
121
+ attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
122
+ return self.wo(attn_output)
123
+
124
+ class FeedForward(nn.Module):
125
+ def __init__(self, config: NexusConfig):
126
+ super().__init__()
127
+ hidden_dim = int(2 * config.ff_dim / 3)
128
+ hidden_dim = config.multiple_of * ((hidden_dim + config.multiple_of - 1) // config.multiple_of)
129
+
130
+ self.w1 = nn.Linear(config.dim, hidden_dim, bias=False)
131
+ self.w2 = nn.Linear(hidden_dim, config.dim, bias=False)
132
+ self.w3 = nn.Linear(config.dim, hidden_dim, bias=False)
133
+
134
+ def forward(self, x):
135
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
136
+
137
+ class TransformerBlock(nn.Module):
138
+ def __init__(self, config: NexusConfig):
139
+ super().__init__()
140
+ self.attention = Attention(config)
141
+ self.feed_forward = FeedForward(config)
142
+ self.attention_norm = RMSNorm(config.dim, config.norm_eps)
143
+ self.ff_norm = RMSNorm(config.dim, config.norm_eps)
144
+
145
+ def forward(self, x: torch.Tensor, start_pos: int = 0, mask: Optional[torch.Tensor] = None):
146
+ h = x + self.attention(self.attention_norm(x), start_pos, mask)
147
+ out = h + self.feed_forward(self.ff_norm(h))
148
+ return out
149
+
150
+ class NexusPreTrainedModel(PreTrainedModel):
151
+ config_class = NexusConfigHF
152
+ base_model_prefix = "nexus_small"
153
+ supports_gradient_checkpointing = False
154
+ _no_split_modules = ["TransformerBlock"]
155
+
156
+ def __init__(self, config: NexusConfigHF):
157
+ super().__init__(config)
158
+ self._nexus_config = NexusConfig(
159
+ vocab_size=config.vocab_size,
160
+ max_seq_len=config.max_seq_len,
161
+ dim=config.dim,
162
+ num_layers=config.num_layers,
163
+ num_heads=config.num_heads,
164
+ num_kv_heads=config.num_kv_heads,
165
+ multiple_of=config.multiple_of,
166
+ ff_dim=config.ff_dim,
167
+ norm_eps=config.norm_eps,
168
+ rope_theta=config.rope_theta,
169
+ )
170
+
171
+ def _init_weights(self, module):
172
+ if isinstance(module, nn.Linear):
173
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
174
+
175
+
176
+ class Nexus(nn.Module):
177
+ def __init__(self, config: NexusConfig):
178
+ super().__init__()
179
+ self.config = config
180
+
181
+ self.token_embeddings = nn.Embedding(config.vocab_size, config.dim)
182
+ self.layers = nn.ModuleList([TransformerBlock(config) for _ in range(config.num_layers)])
183
+ self.norm = RMSNorm(config.dim, config.norm_eps)
184
+ self.output = nn.Linear(config.dim, config.vocab_size, bias=False)
185
+
186
+ self.token_embeddings.weight = self.output.weight
187
+
188
+ self.apply(self._init_weights)
189
+
190
+ def _init_weights(self, module):
191
+ if isinstance(module, nn.Linear):
192
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
193
+
194
+ def forward(self, input_ids: torch.Tensor, start_pos: int = 0):
195
+ _, seqlen = input_ids.shape
196
+
197
+ mask = torch.full((1, 1, seqlen, start_pos + seqlen), float('-inf'),
198
+ dtype=torch.float32, device=input_ids.device)
199
+ mask = torch.triu(mask, diagonal=start_pos + 1).type_as(input_ids)
200
+
201
+ x = self.token_embeddings(input_ids)
202
+
203
+ for layer in self.layers:
204
+ x = layer(x, start_pos, mask)
205
+
206
+ x = self.norm(x)
207
+ logits = self.output(x)
208
+
209
+ return logits
210
+
211
+ def generate(self, input_ids: torch.Tensor, max_new_tokens: int,
212
+ temperature: float = 0.7, top_k: int = 50, top_p: float = 0.9):
213
+ self.eval()
214
+ generated = []
215
+
216
+ for _ in range(max_new_tokens):
217
+ seq_len = input_ids.shape[1]
218
+ if seq_len > self.config.max_seq_len:
219
+ input_ids = input_ids[:, -self.config.max_seq_len:]
220
+
221
+ with torch.no_grad():
222
+ logits = self(input_ids, 0)
223
+ logits = logits[:, -1, :] / temperature
224
+
225
+ if top_k > 0:
226
+ top_k_values, _ = torch.topk(logits, top_k)
227
+ min_top_k = top_k_values[:, -1].unsqueeze(-1)
228
+ logits = torch.where(logits < min_top_k,
229
+ torch.full_like(logits, float('-inf')), logits)
230
+
231
+ if top_p > 0:
232
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
233
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
234
+ sorted_indices_to_remove = cumulative_probs > top_p
235
+ sorted_indices_to_remove[:, 0] = False
236
+ indices_to_remove = torch.zeros_like(logits, dtype=torch.bool)
237
+ indices_to_remove = indices_to_remove.scatter(1, sorted_indices,
238
+ sorted_indices_to_remove)
239
+ logits = torch.where(indices_to_remove,
240
+ torch.full_like(logits, float('-inf')), logits)
241
+
242
+ probs = F.softmax(logits, dim=-1)
243
+ next_token = torch.multinomial(probs, num_samples=1)
244
+
245
+ input_ids = torch.cat([input_ids, next_token], dim=-1)
246
+ generated.append(next_token.item())
247
+
248
+ return generated, input_ids
249
+
250
+ class NexusForCausalLM(NexusPreTrainedModel):
251
+ def __init__(self, config: NexusConfigHF):
252
+ super().__init__(config)
253
+ self.model = Nexus(self._nexus_config)
254
+
255
+ def forward(self, input_ids, attention_mask=None, **kwargs):
256
+ return self.model(input_ids)
257
+
258
+ def generate(self, input_ids, max_new_tokens=128, temperature=0.7, top_k=50, top_p=0.9, **kwargs):
259
+ return self.model.generate(input_ids, max_new_tokens, temperature, top_k, top_p)
260
+
261
+ @classmethod
262
+ def _from_config(cls, config, **kwargs):
263
+ return cls(config)
264
+
265
+ def prepare_inputs_for_generation(self, input_ids, **kwargs):
266
+ return {"input_ids": input_ids}
267
+
268
+
269
+ AutoConfig.register("nexus_small", NexusConfigHF)
270
+ AutoModel.register(NexusConfigHF, NexusForCausalLM)
271
+
272
+
273
+ def create_nexus_model():
274
+ try:
275
+ from config import nexus_config
276
+ except ImportError:
277
+ from .config import nexus_config
278
+ config = nexus_config
279
+
280
+ model = Nexus(config)
281
+ total_params = sum(p.numel() for p in model.parameters())
282
+ trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
283
+
284
+ print(f"[Nexus SmAll] Model created with {total_params/1e6:.1f}M parameters "
285
+ f"({trainable_params/1e6:.1f}M trainable)")
286
+
287
+ return model, config