GRRNMAKER commited on
Commit
bd79d1c
·
verified ·
1 Parent(s): c232435

Upload model_v2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model_v2.py +138 -0
model_v2.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Cozet: Native SYNAXIM Base Model (Enhanced)
3
+ Architecture: SymbioticGate (M-matrix) + NaN Firewall + Dual-Track M
4
+ (c) 2026 GRRN Research.
5
+ """
6
+ import torch, torch.nn as nn, torch.nn.functional as F, math
7
+ from dataclasses import dataclass
8
+
9
+ @dataclass
10
+ class CozConfig:
11
+ hidden_size: int = 1024
12
+ num_layers: int = 12
13
+ num_attention_heads: int = 16
14
+ num_kv_heads: int = 4
15
+ intermediate_size: int = 4096
16
+ vocab_size: int = 50257
17
+ max_seq_len: int = 4096
18
+ rope_theta: float = 10000.0
19
+ rms_norm_eps: float = 1e-6
20
+ memory_decay: float = 0.995
21
+ unrotated_decay: float = 0.995
22
+ tie_word_embeddings: bool = True
23
+ @property
24
+ def head_dim(self):
25
+ return self.hidden_size // self.num_attention_heads
26
+
27
+ class RMSNorm(nn.Module):
28
+ def __init__(self, dim, eps=1e-6):
29
+ super().__init__()
30
+ self.weight = nn.Parameter(torch.ones(dim))
31
+ self.eps = eps
32
+ def forward(self, x):
33
+ return (x.float() * x.float().pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()).type_as(x) * self.weight
34
+
35
+ class NaNFirewall(nn.Module):
36
+ def __init__(self, clamp_value=1e4, norm_ratio=8.0):
37
+ super().__init__()
38
+ self.clamp_value = clamp_value
39
+ self.norm_ratio = norm_ratio
40
+ def forward(self, delta, h_ref):
41
+ delta = torch.nan_to_num(delta, nan=0.0, posinf=self.clamp_value, neginf=-self.clamp_value)
42
+ d_norm = delta.norm()
43
+ max_norm = self.norm_ratio * (h_ref.norm() + 1e-8)
44
+ if d_norm > max_norm:
45
+ delta = delta * (max_norm / (d_norm + 1e-8))
46
+ if torch.isnan(delta).all() or torch.isinf(delta).all():
47
+ delta = torch.zeros_like(delta)
48
+ return delta
49
+
50
+ class SymbioticGate(nn.Module):
51
+ def __init__(self, config, layer_idx):
52
+ super().__init__()
53
+ D, nh, nk, hd = config.hidden_size, config.num_attention_heads, config.num_kv_heads, config.head_dim
54
+ self.D, self.n_heads, self.n_kv, self.head_dim = D, nh, nk, hd
55
+ self.decay = config.memory_decay
56
+ self.unrot_decay = config.unrotated_decay
57
+ self.q_proj = nn.Linear(D, nh * hd, bias=False)
58
+ self.k_proj = nn.Linear(D, nk * hd, bias=False)
59
+ self.v_proj = nn.Linear(D, nk * hd, bias=False)
60
+ self.o_proj = nn.Linear(nh * hd, D, bias=False)
61
+ self.gate_scale = nn.Parameter(torch.ones(1))
62
+ self.gate_bias = nn.Parameter(torch.zeros(1))
63
+ self._rc, self._rs = None, None
64
+ def _rope(self, max_pos, dev):
65
+ if self._rc is not None and max_pos <= self._rc.shape[0]: return
66
+ half = self.head_dim // 2
67
+ f = 1.0 / (10000.0 ** (torch.arange(0, half, device=dev).float() / half))
68
+ a = torch.outer(torch.arange(max_pos, device=dev).float(), f)
69
+ self._rc, self._rs = a.cos(), a.sin()
70
+ def _apply_rope(self, x, pos):
71
+ half = self.head_dim // 2
72
+ c, s = self._rc[pos, :half], self._rs[pos, :half]
73
+ x1, x2 = x[..., :half], x[..., half:]
74
+ return torch.cat([x1*c - x2*s, x1*s + x2*c], dim=-1)
75
+ def forward(self, h, M, M_unrot, pos):
76
+ self._rope(pos + 1, h.device)
77
+ q, k, v = self.q_proj(h), self.k_proj(h), self.v_proj(h)
78
+ q_h = self._apply_rope(q.view(self.n_heads, self.head_dim), pos)
79
+ k_h = self._apply_rope(k.view(self.n_kv, self.head_dim), pos)
80
+ v_h = v.view(self.n_kv, self.head_dim)
81
+ if self.n_kv < self.n_heads:
82
+ r = self.n_heads // self.n_kv
83
+ k_h, v_h = k_h.repeat_interleave(r, 0), v_h.repeat_interleave(r, 0)
84
+ g = torch.sigmoid((q_h * k_h).sum(-1).mean() / math.sqrt(self.head_dim) * self.gate_scale + self.gate_bias)
85
+ kf, vf = k_h.reshape(-1), v_h.reshape(-1)
86
+ kn = kf / (kf.norm() + 1e-8)
87
+ vn = vf / (vf.norm() + 1e-8) * h.norm()
88
+ outer = torch.outer(kn, vn)
89
+ M2 = g * self.decay * M + (1.0 - g) * outer
90
+ M_unrot2 = self.unrot_decay * M_unrot + (1.0 - self.unrot_decay) * outer
91
+ return self.o_proj(q_h.reshape(-1) @ M2), M2, M_unrot2
92
+
93
+ class SynaxBlock(nn.Module):
94
+ def __init__(self, config, i):
95
+ super().__init__()
96
+ self.norm_attn = RMSNorm(config.hidden_size, config.rms_norm_eps)
97
+ self.attn = SymbioticGate(config, i)
98
+ self.norm_mlp = RMSNorm(config.hidden_size, config.rms_norm_eps)
99
+ self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
100
+ self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
101
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
102
+ self.firewall = NaNFirewall()
103
+ def forward(self, h, M, M_unrot, pos):
104
+ a, M2, M_unrot2 = self.attn(self.norm_attn(h), M, M_unrot, pos)
105
+ a = self.firewall(a, h)
106
+ h = h + a
107
+ n = self.norm_mlp(h)
108
+ m = self.down_proj(F.silu(self.gate_proj(n)) * self.up_proj(n))
109
+ m = self.firewall(m, h)
110
+ h = h + m
111
+ return h, M2, M_unrot2
112
+
113
+ class CozModel(nn.Module):
114
+ def __init__(self, config):
115
+ super().__init__()
116
+ self.config, self.D, self.n_layers = config, config.hidden_size, config.num_layers
117
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
118
+ self.layers = nn.ModuleList([SynaxBlock(config, i) for i in range(config.num_layers)])
119
+ self.final_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
120
+ if not config.tie_word_embeddings:
121
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
122
+ ds = 1.0 / math.sqrt(2 * self.n_layers)
123
+ for name, p in self.named_parameters():
124
+ if p.dim() < 2: continue
125
+ if "embed" in name: nn.init.normal_(p, std=0.02)
126
+ elif "down_proj" in name or "o_proj" in name: nn.init.normal_(p, std=0.02 * ds)
127
+ elif p.dim() == 2: nn.init.normal_(p, std=0.02)
128
+ def init_m(self, dev):
129
+ M = [torch.zeros(self.D, self.D, device=dev) for _ in range(self.n_layers)]
130
+ M_unrot = [torch.zeros(self.D, self.D, device=dev) for _ in range(self.n_layers)]
131
+ return M, M_unrot
132
+ def forward_token(self, tid, M, M_unrot, pos):
133
+ h = self.embed_tokens.weight[tid]
134
+ for i, layer in enumerate(self.layers):
135
+ h, M[i], M_unrot[i] = layer(h, M[i], M_unrot[i], pos)
136
+ h = self.final_norm(h)
137
+ logits = h @ self.embed_tokens.weight.T if self.config.tie_word_embeddings else self.lm_head(h)
138
+ return logits, M, M_unrot