kgrabko commited on
Commit
38a6e7c
·
verified ·
1 Parent(s): 9ca2193

Create JiRackTernaryPyTorch_1b.py

Browse files
Files changed (1) hide show
  1. JiRackTernaryPyTorch_1b.py +156 -0
JiRackTernaryPyTorch_1b.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # COPYRIGHT © 2025 Konstantin Vladimirovich Grabko. ALL RIGHTS RESERVED.
3
+ # CMS Manhattan JiRack Technology — PATENT PENDING
4
+ #
5
+ # This code is proprietary.
6
+ # Personal and non-commercial research use is allowed.
7
+ # Any commercial use, derivative works for profit, or distribution
8
+ # requires a paid license and 5% royalty.
9
+ #
10
+ # Unauthorized commercial use is strictly prohibited.
11
+ # Contact: grabko@cmsmanhattan.com
12
+ # =============================================================================
13
+ #
14
+ # Model updated for new last tokenizer version
15
+ #
16
+ # Replace toknizer in current model: Just use the class and call resize function in your train script
17
+ # New model: Use our conversion script to rapidly initialize new models by copying existing embeddings and LM_head weights. This enables fast model bootstrapping, or alternatively, provides the foundation to train a new model entirely from scratch.
18
+ #
19
+ # =============================================================================
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+
25
+ # --- JIRACK 1B ARCHITECTURE CONSTANTS ---
26
+ VOCAB_SIZE = 128259
27
+ HIDDEN_SIZE = 2048
28
+ NUM_LAYERS = 16
29
+ NUM_HEADS = 32
30
+ NUM_KV_HEADS = 8
31
+ INTERMEDIATE_SIZE = 8192
32
+ MAX_SEQ_LEN = 4096
33
+ RMS_EPS = 1e-6
34
+
35
+ # --- QUANTIZATION PARAMETERS ---
36
+ STABILITY_EPS = 1e-9
37
+ INT8_SCALE_TARGET = 127.0
38
+
39
+ class TernaryConfig:
40
+ def __init__(self):
41
+ self.vocab_size = VOCAB_SIZE
42
+ self.hidden_size = HIDDEN_SIZE
43
+ self.num_hidden_layers = NUM_LAYERS
44
+ self.num_attention_heads = NUM_HEADS
45
+ self.num_key_value_heads = NUM_KV_HEADS
46
+ self.intermediate_size = INTERMEDIATE_SIZE
47
+ self.max_position_embeddings = MAX_SEQ_LEN
48
+ self.rms_norm_eps = RMS_EPS
49
+
50
+ class BitLinear(nn.Linear):
51
+ def __init__(self, in_features, out_features, bias=False):
52
+ super().__init__(in_features, out_features, bias)
53
+
54
+ def forward(self, x):
55
+ # Weight Quantization
56
+ w = self.weight
57
+ gamma = w.abs().mean().clamp(min=STABILITY_EPS)
58
+ w_quant = torch.clamp(torch.round(w / gamma), -1, 1)
59
+ w_final = w + (w_quant * gamma - w).detach()
60
+
61
+ # Activation Quantization (Absmax)
62
+ x_norm = x - x.mean(dim=-1, keepdim=True)
63
+ x_max = x_norm.abs().max(dim=-1, keepdim=True).values.clamp(min=STABILITY_EPS)
64
+ scale = INT8_SCALE_TARGET / x_max
65
+ x_quant = (x_norm * scale).round().clamp(-128, 127) / scale
66
+ x_final = x + (x_quant - x).detach()
67
+
68
+ return F.linear(x_final, w_final, self.bias)
69
+
70
+ class RMSNorm(nn.Module):
71
+ def __init__(self, dim, eps=RMS_EPS):
72
+ super().__init__()
73
+ self.eps = eps
74
+ self.weight = nn.Parameter(torch.ones(dim))
75
+ def forward(self, x):
76
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
77
+
78
+ # --- ROPE WITHOUT COMPLEX NUMBERS ---
79
+ def precompute_freqs_cis(dim, seq_len, theta=500000.0):
80
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
81
+ t = torch.arange(seq_len).float()
82
+ freqs = torch.outer(t, freqs)
83
+ return torch.cos(freqs), torch.sin(freqs)
84
+
85
+ def apply_rotary_emb(xq, xk, freqs_cos, freqs_sin):
86
+ def rotate_half(x):
87
+ # Split 64 into two 32s
88
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
89
+ return torch.cat((-x2, x1), dim=-1)
90
+
91
+ T = xq.shape[2]
92
+ # FIX: Repeat frequencies (32 -> 64) to match head_dim
93
+ f_cos = freqs_cos[:T].to(xq.device).view(1, 1, T, -1).repeat(1, 1, 1, 2)
94
+ f_sin = freqs_sin[:T].to(xq.device).view(1, 1, T, -1).repeat(1, 1, 1, 2)
95
+
96
+ xq_out = (xq * f_cos) + (rotate_half(xq) * f_sin)
97
+ xk_out = (xk * f_cos) + (rotate_half(xk) * f_sin)
98
+ return xq_out, xk_out
99
+
100
+ def repeat_kv(x, n_rep):
101
+ if n_rep == 1: return x
102
+ bs, n_kv_heads, seqlen, head_dim = x.shape
103
+ return x[:, :, None, :, :].expand(bs, n_kv_heads, n_rep, seqlen, head_dim).reshape(bs, n_kv_heads * n_rep, seqlen, head_dim)
104
+
105
+ class TransformerBlock(nn.Module):
106
+ def __init__(self, config):
107
+ super().__init__()
108
+ self.n_heads = config.num_attention_heads
109
+ self.n_kv_heads = config.num_key_value_heads
110
+ self.n_rep = self.n_heads // self.n_kv_heads
111
+ self.head_dim = config.hidden_size // self.n_heads
112
+ self.q_proj = BitLinear(config.hidden_size, config.hidden_size)
113
+ self.k_proj = BitLinear(config.hidden_size, self.n_kv_heads * self.head_dim)
114
+ self.v_proj = BitLinear(config.hidden_size, self.n_kv_heads * self.head_dim)
115
+ self.out_proj = BitLinear(config.hidden_size, config.hidden_size)
116
+ self.ffn_w1 = BitLinear(config.hidden_size, config.intermediate_size)
117
+ self.ffn_w3 = BitLinear(config.hidden_size, config.intermediate_size)
118
+ self.ffn_w2 = BitLinear(config.intermediate_size, config.hidden_size)
119
+ self.norm1 = RMSNorm(config.hidden_size)
120
+ self.norm2 = RMSNorm(config.hidden_size)
121
+
122
+ def forward(self, x, freqs_cos, freqs_sin):
123
+ h = self.norm1(x)
124
+ B, T, D = x.shape
125
+ q = self.q_proj(h).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
126
+ k = self.k_proj(h).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
127
+ v = self.v_proj(h).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
128
+
129
+ q, k = apply_rotary_emb(q, k, freqs_cos, freqs_sin)
130
+
131
+ k, v = repeat_kv(k, self.n_rep), repeat_kv(v, self.n_rep)
132
+ attn_out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
133
+
134
+ x = x + self.out_proj(attn_out.transpose(1, 2).reshape(B, T, D))
135
+ m = self.norm2(x)
136
+ x = x + self.ffn_w2(F.silu(self.ffn_w1(m)) * self.ffn_w3(m))
137
+ return x
138
+
139
+ class TernaryTransformer1B(nn.Module):
140
+ def __init__(self, config):
141
+ super().__init__()
142
+ self.token_emb = nn.Embedding(config.vocab_size, config.hidden_size)
143
+ self.blocks = nn.ModuleList([TransformerBlock(config) for _ in range(config.num_hidden_layers)])
144
+ self.ln_f = RMSNorm(config.hidden_size)
145
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
146
+
147
+ # RoPE frequencies (64 head_dim -> 32 pairs)
148
+ cos, sin = precompute_freqs_cis(config.hidden_size // config.num_attention_heads, MAX_SEQ_LEN)
149
+ self.register_buffer("freqs_cos", cos)
150
+ self.register_buffer("freqs_sin", sin)
151
+
152
+ def forward(self, input_ids):
153
+ x = self.token_emb(input_ids)
154
+ for block in self.blocks:
155
+ x = block(x, self.freqs_cos, self.freqs_sin)
156
+ return self.lm_head(self.ln_f(x)), None