Harley-ml commited on
Commit
bd979f8
·
verified ·
1 Parent(s): cd05f07

Upload 5 files

Browse files
Files changed (3) hide show
  1. config.json +35 -35
  2. configuration_negative.py +59 -0
  3. modeling_negative.py +476 -0
config.json CHANGED
@@ -1,36 +1,36 @@
1
- {
2
- "architectures": [
3
- "CustomModelForCausalLM"
4
- ],
5
- "auto_map": {
6
- "AutoConfig": "configuration_custom.CustomConfig",
7
- "AutoModel": "modeling_custom.CustomModel",
8
- "AutoModelForCausalLM": "modeling_custom.CustomModelForCausalLM"
9
- },
10
- "dtype": "float32",
11
- "engram_entries": 196,
12
- "engram_ngram_orders": [
13
- 4,
14
- 8
15
- ],
16
- "head_dim": 8,
17
- "hidden_size": 32,
18
- "initializer_range": 0.02,
19
- "intermediate_size": 64,
20
- "max_position_embeddings": 96,
21
- "model_type": "custom_model",
22
- "num_attention_heads": 4,
23
- "num_hidden_layers": 9,
24
- "num_key_value_heads": 2,
25
- "num_lanes": 8,
26
- "rms_norm_eps": 1e-05,
27
- "rope_theta": 2500.0,
28
- "swiglu_interval": 4,
29
- "tie_word_embeddings": true,
30
- "transformers_version": "5.8.0.dev0",
31
- "use_cache": false,
32
- "use_engram": true,
33
- "use_per_head_gating": false,
34
- "use_xsa": false,
35
- "vocab_size": 260
36
  }
 
1
+ {
2
+ "architectures": [
3
+ "NegativeModelForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_negative.NegativeConfig",
7
+ "AutoModel": "modeling_negative.NegativeModel",
8
+ "AutoModelForCausalLM": "modeling_negative.NegativeModelForCausalLM"
9
+ },
10
+ "dtype": "float32",
11
+ "engram_entries": 196,
12
+ "engram_ngram_orders": [
13
+ 4,
14
+ 8
15
+ ],
16
+ "head_dim": 8,
17
+ "hidden_size": 32,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 64,
20
+ "max_position_embeddings": 96,
21
+ "model_type": "negative",
22
+ "num_attention_heads": 4,
23
+ "num_hidden_layers": 9,
24
+ "num_key_value_heads": 2,
25
+ "num_lanes": 8,
26
+ "rms_norm_eps": 1e-05,
27
+ "rope_theta": 2500.0,
28
+ "swiglu_interval": 4,
29
+ "tie_word_embeddings": true,
30
+ "transformers_version": "5.8.0.dev0",
31
+ "use_cache": false,
32
+ "use_engram": true,
33
+ "use_per_head_gating": false,
34
+ "use_xsa": false,
35
+ "vocab_size": 260
36
  }
configuration_negative.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from typing import Tuple, List, Optional
3
+
4
+ class NegativeConfig(PretrainedConfig):
5
+ model_type = "negative"
6
+ keys_to_ignore_at_inference = ["past_key_values"]
7
+
8
+ def __init__(
9
+ self,
10
+ vocab_size: int = 2564,
11
+ hidden_size: int = 128,
12
+ num_hidden_layers: int = 21,
13
+ num_attention_heads: int = 4,
14
+ num_key_value_heads: int = 2,
15
+ intermediate_size: int = 345,
16
+ swiglu_interval: int = 3,
17
+ num_lanes: int = 4,
18
+ use_engram: bool = True,
19
+ engram_entries: int = 2400,
20
+ engram_ngram_orders: Tuple[int, ...] = (2, 3),
21
+ use_xsa: bool = False,
22
+ use_per_head_gating: bool = False,
23
+ max_position_embeddings: int = 2048,
24
+ rope_theta: float = 2500.0,
25
+ rms_norm_eps: float = 1e-5,
26
+ tie_word_embeddings: bool = True,
27
+ use_cache: bool = False,
28
+ initializer_range: float = 0.02,
29
+ **kwargs,
30
+ ):
31
+ self.vocab_size = vocab_size
32
+ self.hidden_size = hidden_size
33
+ self.num_hidden_layers = num_hidden_layers
34
+ self.num_attention_heads = num_attention_heads
35
+ self.num_key_value_heads = num_key_value_heads
36
+ self.intermediate_size = intermediate_size
37
+ self.swiglu_interval = swiglu_interval
38
+ self.num_lanes = num_lanes
39
+ self.use_engram = use_engram
40
+ self.engram_entries = engram_entries
41
+ self.engram_ngram_orders = list(engram_ngram_orders)
42
+ self.use_xsa = use_xsa
43
+ self.use_per_head_gating = use_per_head_gating
44
+ self.max_position_embeddings = max_position_embeddings
45
+ self.rope_theta = rope_theta
46
+ self.rms_norm_eps = rms_norm_eps
47
+ self.initializer_range = initializer_range
48
+ self.head_dim = hidden_size // num_attention_heads
49
+ self.auto_map = {
50
+ "AutoConfig": "configuration_negative.NegativeConfig",
51
+ "AutoModel": "modeling_negative.NegativeModel",
52
+ "AutoModelForCausalLM": "modeling_negative.NegativeModelForCausalLM",
53
+ }
54
+
55
+ super().__init__(
56
+ tie_word_embeddings=tie_word_embeddings,
57
+ use_cache=use_cache,
58
+ **kwargs,
59
+ )
modeling_negative.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ from typing import Optional, Tuple, Union
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import torch.utils.checkpoint as cp
8
+ from transformers.modeling_utils import PreTrainedModel
9
+ from transformers.modeling_outputs import CausalLMOutputWithPast
10
+ from transformers.generation import GenerationMixin
11
+ from safetensors.torch import load_file
12
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
13
+
14
+ from .configuration_negative import NegativeConfig
15
+
16
+ @torch.no_grad()
17
+ def get_hadamard_matrix(d: int, dtype=torch.float32) -> torch.Tensor:
18
+ eye = torch.eye(d, dtype=dtype)
19
+ h = 1
20
+ out = eye.clone()
21
+ while h < d:
22
+ out = out.view(-1, 2, h)
23
+ u = out[:, 0, :]
24
+ v = out[:, 1, :]
25
+ out = torch.cat((u + v, u - v), dim=-2)
26
+ out = out.view(d, d)
27
+ h *= 2
28
+ return (out * (1.0 / math.sqrt(d))).contiguous()
29
+
30
+ class HadamardMLP(nn.Module):
31
+ def __init__(self, config: NegativeConfig):
32
+ super().__init__()
33
+ self.dim = config.hidden_size
34
+ self.scale1 = nn.Parameter(torch.ones(self.dim))
35
+ self.scale2 = nn.Parameter(torch.ones(self.dim))
36
+ self.gate = nn.Parameter(torch.ones(self.dim))
37
+ self.bias = nn.Parameter(torch.zeros(self.dim))
38
+
39
+ hadamard_mat = get_hadamard_matrix(self.dim)
40
+ self.register_buffer("hadamard_mat", hadamard_mat, persistent=False)
41
+
42
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
43
+ mat = self.hadamard_mat.type_as(x)
44
+ h = (x * self.scale1) @ mat
45
+ g = F.silu(x * self.gate)
46
+ out = ((h * g) @ mat) * self.scale2 + self.bias
47
+ return out
48
+
49
+ class SwiGLUMLP(nn.Module):
50
+ def __init__(self, config: NegativeConfig):
51
+ super().__init__()
52
+ self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
53
+ self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
54
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
55
+
56
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
57
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
58
+
59
+ class EngramMemory(nn.Module):
60
+ def __init__(self, config: NegativeConfig):
61
+ super().__init__()
62
+ self.dim = config.hidden_size
63
+ self.num_entries = config.engram_entries
64
+ self.n_gram_orders = config.engram_ngram_orders
65
+
66
+ self.tables = nn.ModuleList([
67
+ nn.Embedding(self.num_entries, self.dim) for _ in self.n_gram_orders
68
+ ])
69
+ self.gate_proj = nn.Linear(self.dim, self.dim * len(self.n_gram_orders), bias=False)
70
+ self.out_proj = nn.Linear(self.dim * len(self.n_gram_orders), self.dim, bias=False)
71
+
72
+ def _hash_ngram(self, tokens: torch.Tensor, order: int, table_idx: int) -> torch.Tensor:
73
+ bsz, seqlen = tokens.shape
74
+ padded = F.pad(tokens, (order - 1, 0), value=0)
75
+ primes = (10007, 10009, 10037, 10039, 10061, 10067)
76
+ p = primes[table_idx % len(primes)]
77
+
78
+ if order == 2:
79
+ return (padded[:, :seqlen] * p + padded[:, 1 : seqlen + 1]) % self.num_entries
80
+ elif order == 3:
81
+ h = (padded[:, :seqlen] * p + padded[:, 1 : seqlen + 1]) % self.num_entries
82
+ return (h * p + padded[:, 2 : seqlen + 2]) % self.num_entries
83
+ else:
84
+ hash_val = torch.zeros((bsz, seqlen), dtype=torch.int64, device=tokens.device)
85
+ for k in range(order):
86
+ tok = padded[:, k : k + seqlen]
87
+ hash_val = (hash_val * p + tok) % self.num_entries
88
+ return hash_val
89
+
90
+ def forward(self, x: torch.Tensor, tokens: torch.Tensor) -> torch.Tensor:
91
+ mem_lookups = [self.tables[i](self._hash_ngram(tokens, order, i)) for i, order in enumerate(self.n_gram_orders)]
92
+ concat_mem = torch.cat(mem_lookups, dim=-1)
93
+ gate = torch.sigmoid(self.gate_proj(x))
94
+ return self.out_proj(concat_mem * gate)
95
+
96
+ class RMSNorm(nn.Module):
97
+ def __init__(self, dim: int, eps: float = 1e-5):
98
+ super().__init__()
99
+ self.eps = eps
100
+ self.weight = nn.Parameter(torch.ones(dim))
101
+
102
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
103
+ norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
104
+ return x * norm * self.weight
105
+
106
+ class RotaryEmbedding(nn.Module):
107
+ def __init__(self, dim: int, max_position_embeddings: int = 2048, base: float = 10000.0):
108
+ super().__init__()
109
+ self.dim = dim
110
+ self.max_position_embeddings = max_position_embeddings
111
+ self.base = base
112
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.float32) / self.dim))
113
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
114
+ self._set_cos_sin_cache(max_position_embeddings)
115
+
116
+ def _set_cos_sin_cache(self, seq_len: int, device=None, dtype=torch.float32):
117
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
118
+ inv_freq = self.inv_freq.to(device=device, dtype=torch.float32)
119
+ freqs = torch.outer(t, inv_freq)
120
+ emb = torch.cat((freqs, freqs), dim=-1)
121
+ self.register_buffer("cos_cached", emb.cos().to(dtype=dtype), persistent=False)
122
+ self.register_buffer("sin_cached", emb.sin().to(dtype=dtype), persistent=False)
123
+
124
+ def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype = torch.float32):
125
+ if not hasattr(self, "cos_cached") or seq_len > self.cos_cached.shape[0] or self.cos_cached.device != device:
126
+ self._set_cos_sin_cache(seq_len, device=device, dtype=dtype)
127
+ return (
128
+ self.cos_cached[:seq_len].to(device=device, dtype=dtype),
129
+ self.sin_cached[:seq_len].to(device=device, dtype=dtype),
130
+ )
131
+
132
+ def rotate_half(x: torch.Tensor) -> torch.Tensor:
133
+ x1 = x[..., : x.shape[-1] // 2]
134
+ x2 = x[..., x.shape[-1] // 2 :]
135
+ return torch.cat((-x2, x1), dim=-1)
136
+
137
+ def apply_rotary_pos_emb(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
138
+ q_embed = (q * cos) + (rotate_half(q) * sin)
139
+ k_embed = (k * cos) + (rotate_half(k) * sin)
140
+ return q_embed, k_embed
141
+
142
+ class XSAGQAttention(nn.Module):
143
+ def __init__(self, config: NegativeConfig):
144
+ super().__init__()
145
+ self.dim = config.hidden_size
146
+ self.n_heads = config.num_attention_heads
147
+ self.n_kv_heads = config.num_key_value_heads
148
+ self.head_dim = config.head_dim
149
+ self.num_kv_groups = self.n_heads // self.n_kv_heads
150
+ self.use_xsa = config.use_xsa
151
+ self.use_per_head_gating = config.use_per_head_gating
152
+
153
+ self.wq = nn.Linear(self.dim, self.n_heads * self.head_dim, bias=False)
154
+ self.wk = nn.Linear(self.dim, self.n_kv_heads * self.head_dim, bias=False)
155
+ self.wv = nn.Linear(self.dim, self.n_kv_heads * self.head_dim, bias=False)
156
+ self.wo = nn.Linear(self.n_heads * self.head_dim, self.dim, bias=False)
157
+
158
+ self.q_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
159
+ self.k_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
160
+
161
+ if self.use_per_head_gating:
162
+ self.head_gate = nn.Linear(self.dim, self.n_heads, bias=True)
163
+ nn.init.constant_(self.head_gate.bias, 1.0)
164
+ nn.init.zeros_(self.head_gate.weight)
165
+
166
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
167
+ bsz, seqlen, _ = x.shape
168
+
169
+ xq = self.wq(x).view(bsz, seqlen, self.n_heads, self.head_dim).transpose(1, 2)
170
+ xk = self.wk(x).view(bsz, seqlen, self.n_kv_heads, self.head_dim).transpose(1, 2)
171
+ xv = self.wv(x).view(bsz, seqlen, self.n_kv_heads, self.head_dim).transpose(1, 2)
172
+
173
+ xq = self.q_norm(xq)
174
+ xk = self.k_norm(xk)
175
+
176
+ xq, xk = apply_rotary_pos_emb(xq, xk, cos, sin)
177
+
178
+ if self.num_kv_groups > 1:
179
+ xk = xk.repeat_interleave(self.num_kv_groups, dim=1)
180
+ xv_expanded = xv.repeat_interleave(self.num_kv_groups, dim=1)
181
+ else:
182
+ xv_expanded = xv
183
+
184
+ attn_out = F.scaled_dot_product_attention(xq, xk, xv_expanded, is_causal=True)
185
+
186
+ if self.use_xsa:
187
+ vn = F.normalize(xv_expanded, p=2, dim=-1, eps=1e-6)
188
+ proj = (attn_out * vn).sum(dim=-1, keepdim=True)
189
+ attn_out = attn_out - proj * vn
190
+
191
+ if self.use_per_head_gating:
192
+ gate = torch.sigmoid(self.head_gate(x)).transpose(1, 2).unsqueeze(-1)
193
+ attn_out = attn_out * gate
194
+
195
+ out = attn_out.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
196
+ return self.wo(out)
197
+
198
+
199
+ class MultiLaneBlock(nn.Module):
200
+ def __init__(self, config: NegativeConfig, layer_idx: int):
201
+ super().__init__()
202
+ self.num_lanes = config.num_lanes
203
+ self.dim = config.hidden_size
204
+ self.layer_idx = layer_idx
205
+
206
+ self.attn_norm = RMSNorm(self.dim, eps=config.rms_norm_eps)
207
+ self.attn = XSAGQAttention(config)
208
+
209
+ self.mlp_norm = RMSNorm(self.dim, eps=config.rms_norm_eps)
210
+ if config.swiglu_interval == 0:
211
+ self.use_swiglu = False
212
+ elif config.swiglu_interval == 1:
213
+ self.use_swiglu = True
214
+ else:
215
+ self.use_swiglu = ((layer_idx + 1) % config.swiglu_interval == 0)
216
+
217
+ if self.use_swiglu:
218
+ self.mlp = SwiGLUMLP(config)
219
+ else:
220
+ self.mlp = HadamardMLP(config)
221
+
222
+ self.lane_mix_attn = nn.Parameter(torch.eye(self.num_lanes) + 0.05 * torch.randn(self.num_lanes, self.num_lanes))
223
+ self.lane_mix_mlp = nn.Parameter(torch.eye(self.num_lanes) + 0.05 * torch.randn(self.num_lanes, self.num_lanes))
224
+
225
+ def forward(self, lanes: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
226
+ primary = lanes[0]
227
+ attn_update = self.attn(self.attn_norm(primary), cos, sin)
228
+
229
+ mixed = torch.matmul(self.lane_mix_attn, lanes.view(self.num_lanes, -1)).view_as(lanes)
230
+ lanes = torch.cat([(mixed[0] + attn_update).unsqueeze(0), mixed[1:]], dim=0)
231
+
232
+ mlp_update = self.mlp(self.mlp_norm(lanes[0]))
233
+ mixed = torch.matmul(self.lane_mix_mlp, lanes.view(self.num_lanes, -1)).view_as(lanes)
234
+ lanes = torch.cat([(mixed[0] + mlp_update).unsqueeze(0), mixed[1:]], dim=0)
235
+ return lanes
236
+
237
+ class NegativePreTrainedModel(PreTrainedModel):
238
+ config_class = NegativeConfig
239
+ base_model_prefix = "model"
240
+ supports_gradient_checkpointing = True
241
+ _no_split_modules = ["MultiLaneBlock"]
242
+
243
+ def _init_weights(self, module):
244
+ std = self.config.initializer_range
245
+ if isinstance(module, (nn.Linear, nn.Embedding)):
246
+ module.weight.data.normal_(mean=0.0, std=std)
247
+ if hasattr(module, "bias") and module.bias is not None:
248
+ module.bias.data.zero_()
249
+ elif isinstance(module, RMSNorm):
250
+ module.weight.data.fill_(1.0)
251
+
252
+ @classmethod
253
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
254
+ config = kwargs.pop("config", None)
255
+ kwargs.pop("trust_remote_code", None)
256
+ torch_dtype = kwargs.pop("torch_dtype", None)
257
+ kwargs.pop("device_map", None)
258
+ kwargs.pop("low_cpu_mem_usage", None)
259
+
260
+ if config is None:
261
+ config = NegativeConfig.from_pretrained(pretrained_model_name_or_path)
262
+
263
+ model = cls(config, *model_args)
264
+
265
+ st_file = None
266
+ bin_file = None
267
+
268
+ if os.path.isdir(str(pretrained_model_name_or_path)):
269
+ local_st = os.path.join(pretrained_model_name_or_path, "model.safetensors")
270
+ local_bin = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin")
271
+ if os.path.exists(local_st):
272
+ st_file = local_st
273
+ elif os.path.exists(local_bin):
274
+ bin_file = local_bin
275
+ else:
276
+ try:
277
+ from huggingface_hub import hf_hub_download
278
+ st_file = hf_hub_download(repo_id=str(pretrained_model_name_or_path), filename="model.safetensors")
279
+ except Exception:
280
+ try:
281
+ bin_file = hf_hub_download(repo_id=str(pretrained_model_name_or_path), filename="pytorch_model.bin")
282
+ except Exception:
283
+ pass
284
+
285
+ if st_file and os.path.exists(st_file):
286
+ state_dict = load_file(st_file)
287
+ model.load_state_dict(state_dict, strict=False)
288
+ elif bin_file and os.path.exists(bin_file):
289
+ state_dict = torch.load(bin_file, map_location="cpu")
290
+ model.load_state_dict(state_dict, strict=False)
291
+ else:
292
+ return super().from_pretrained(pretrained_model_name_or_path, *model_args, config=config, **kwargs)
293
+
294
+ if getattr(config, "tie_word_embeddings", True) and hasattr(model, "lm_head") and hasattr(model, "model"):
295
+ model.lm_head.weight = model.model.embed_tokens.weight
296
+
297
+ if torch_dtype is not None:
298
+ model.to(dtype=torch_dtype)
299
+
300
+ return model
301
+
302
+ class NegativeModel(NegativePreTrainedModel):
303
+ def __init__(self, config: NegativeConfig, *args, **kwargs):
304
+ super().__init__(config)
305
+ self.config = config
306
+ self.num_lanes = config.num_lanes
307
+ self.gradient_checkpointing = False
308
+
309
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
310
+ if config.use_engram:
311
+ self.engram = EngramMemory(config)
312
+ self.engram_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
313
+ else:
314
+ self.engram = None
315
+ self.engram_norm = None
316
+
317
+ self.layers = nn.ModuleList([
318
+ MultiLaneBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)
319
+ ])
320
+
321
+ # Enhanced Lane Pooling: Learned softmax combination of all 3 lanes before norm
322
+ self.lane_pool_weights = nn.Parameter(torch.tensor([1.0] + [0.1] * (config.num_lanes - 1)))
323
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
324
+ self.rotary_emb = RotaryEmbedding(config.head_dim, config.max_position_embeddings, config.rope_theta)
325
+
326
+ self.post_init()
327
+
328
+ def get_input_embeddings(self):
329
+ return self.embed_tokens
330
+
331
+ def set_input_embeddings(self, value):
332
+ self.embed_tokens = value
333
+
334
+ def forward(
335
+ self,
336
+ input_ids: torch.LongTensor = None,
337
+ attention_mask: Optional[torch.Tensor] = None,
338
+ position_ids: Optional[torch.LongTensor] = None,
339
+ inputs_embeds: Optional[torch.FloatTensor] = None,
340
+ use_cache: Optional[bool] = None,
341
+ output_attentions: Optional[bool] = None,
342
+ output_hidden_states: Optional[bool] = None,
343
+ return_dict: Optional[bool] = None,
344
+ ):
345
+ if input_ids is not None:
346
+ bsz, seqlen = input_ids.shape
347
+ h0 = self.embed_tokens(input_ids)
348
+ tokens_for_engram = input_ids
349
+ elif inputs_embeds is not None:
350
+ bsz, seqlen, _ = inputs_embeds.shape
351
+ h0 = inputs_embeds
352
+ tokens_for_engram = torch.zeros((bsz, seqlen), dtype=torch.long, device=inputs_embeds.device)
353
+ else:
354
+ raise ValueError("You must specify either input_ids or inputs_embeds")
355
+
356
+ if self.engram is not None:
357
+ engram_out = self.engram(self.engram_norm(h0), tokens_for_engram)
358
+ h0 = h0 + engram_out
359
+
360
+ lanes = h0.unsqueeze(0).repeat(self.num_lanes, 1, 1, 1)
361
+
362
+ cos, sin = self.rotary_emb(seqlen, device=h0.device, dtype=h0.dtype)
363
+ cos = cos.unsqueeze(0).unsqueeze(0)
364
+ sin = sin.unsqueeze(0).unsqueeze(0)
365
+
366
+ for layer in self.layers:
367
+ if self.gradient_checkpointing and self.training:
368
+ lanes = cp.checkpoint(layer, lanes, cos, sin, use_reentrant=False)
369
+ else:
370
+ lanes = layer(lanes, cos, sin)
371
+
372
+ # Weighted lane pooling for higher representation power
373
+ pool_weights = F.softmax(self.lane_pool_weights, dim=0).view(self.num_lanes, 1, 1, 1)
374
+ pooled = (lanes * pool_weights).sum(dim=0)
375
+ out = self.norm(pooled)
376
+ return out
377
+
378
+ class NegativeModelForCausalLM(NegativePreTrainedModel, GenerationMixin):
379
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
380
+ _keys_to_ignore_on_load_missing = ["lm_head.weight"]
381
+ supports_gradient_checkpointing = True
382
+
383
+ def __init__(self, config: NegativeConfig, *args, **kwargs):
384
+ super().__init__(config)
385
+ self.model = NegativeModel(config)
386
+ self.vocab_size = config.vocab_size
387
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
388
+
389
+ self.post_init()
390
+
391
+ def get_input_embeddings(self):
392
+ return self.model.embed_tokens
393
+
394
+ def set_input_embeddings(self, value):
395
+ self.model.embed_tokens = value
396
+
397
+ def get_output_embeddings(self):
398
+ return self.lm_head
399
+
400
+ def set_output_embeddings(self, new_embeddings):
401
+ self.lm_head = new_embeddings
402
+
403
+ def prepare_inputs_for_generation(
404
+ self,
405
+ input_ids,
406
+ past_key_values=None,
407
+ attention_mask=None,
408
+ inputs_embeds=None,
409
+ **kwargs,
410
+ ):
411
+ if inputs_embeds is not None and past_key_values is None:
412
+ model_inputs = {"inputs_embeds": inputs_embeds}
413
+ else:
414
+ model_inputs = {"input_ids": input_ids}
415
+
416
+ model_inputs.update({
417
+ "attention_mask": attention_mask,
418
+ "use_cache": False,
419
+ })
420
+ return model_inputs
421
+
422
+ def forward(
423
+ self,
424
+ input_ids: torch.LongTensor = None,
425
+ attention_mask: Optional[torch.Tensor] = None,
426
+ position_ids: Optional[torch.LongTensor] = None,
427
+ inputs_embeds: Optional[torch.FloatTensor] = None,
428
+ labels: Optional[torch.LongTensor] = None,
429
+ use_cache: Optional[bool] = None,
430
+ output_attentions: Optional[bool] = None,
431
+ output_hidden_states: Optional[bool] = None,
432
+ return_dict: Optional[bool] = None,
433
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
434
+ return_dict = return_dict if return_dict is not None else getattr(self.config, "return_dict", True)
435
+
436
+ hidden_states = self.model(
437
+ input_ids=input_ids,
438
+ attention_mask=attention_mask,
439
+ position_ids=position_ids,
440
+ inputs_embeds=inputs_embeds,
441
+ use_cache=use_cache,
442
+ output_attentions=output_attentions,
443
+ output_hidden_states=output_hidden_states,
444
+ return_dict=return_dict,
445
+ )
446
+
447
+ logits = self.lm_head(hidden_states)
448
+ logits = logits.float()
449
+
450
+ loss = None
451
+ if labels is not None:
452
+ shift_logits = logits[..., :-1, :].contiguous()
453
+ shift_labels = labels[..., 1:].contiguous()
454
+ loss = F.cross_entropy(
455
+ shift_logits.view(-1, self.config.vocab_size),
456
+ shift_labels.view(-1),
457
+ ignore_index=-100
458
+ )
459
+
460
+ if not return_dict:
461
+ output = (logits,)
462
+ return ((loss,) + output) if loss is not None else output
463
+
464
+ return CausalLMOutputWithPast(
465
+ loss=loss,
466
+ logits=logits,
467
+ past_key_values=None,
468
+ hidden_states=None,
469
+ attentions=None,
470
+ )
471
+
472
+
473
+
474
+ AutoConfig.register("negative", NegativeConfig)
475
+ AutoModel.register(NegativeConfig, NegativeModel)
476
+ AutoModelForCausalLM.register(NegativeConfig, NegativeModelForCausalLM)