tarekfurthy commited on
Commit
b3b7317
·
verified ·
1 Parent(s): ec55f4d

Upload UPLOAD_1_trnr_ship.py

Browse files
Files changed (1) hide show
  1. UPLOAD_1_trnr_ship.py +941 -0
UPLOAD_1_trnr_ship.py ADDED
@@ -0,0 +1,941 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # trnr / UPLOAD_1_trnr_ship.py -- ONE file, self-contained. Get this single file onto the Kaggle
2
+ # machine (notebook file browser into /kaggle/working, or attach it as a Kaggle Dataset; the runner
3
+ # cell looks in both), then run the runner cell.
4
+ #
5
+ # It writes the four companion files it needs from embedded source, syntax-checks them, and runs
6
+ # the whole pipeline: environment, generate the ternary model, validate, upload to HuggingFace,
7
+ # package the llama.cpp fork. ~35 min.
8
+ #
9
+ # Why it is one file: the sources total 39 KB and a chat paste that survives is ~6 KB, so they
10
+ # cannot be handed over as text. A file has no such limit.
11
+ #
12
+ # SECURITY: HF_TOKEN below is FULL-ACCESS. Rotate it at huggingface.co/settings/tokens the moment
13
+ # this finishes.
14
+ import ast, os, re, sys, glob, json, shutil, pickle, tarfile, subprocess
15
+ import numpy as np
16
+ K = "/kaggle/working"; W = "/tmp/trnr"; SRC = W + "/llama.cpp"
17
+ PIN = "16f090f92c0e2ac6dfddcaf93589a9b158c598c7"
18
+ MID = "allenai/OLMoE-1B-7B-0125-Instruct"
19
+ HF_TOKEN = "__HF_TOKEN__" # injected by the runner cell; a real token here makes
20
+ # HuggingFace REJECT the upload (its secret scanner).
21
+ REPO_NAME = "OLMoE-1B-7B-0125-Instruct-ternary-tq1_0"
22
+ B = lambda t: print("=" * 70 + "\n" + t + "\n" + "=" * 70, flush=True)
23
+ P = lambda s: print(" " + s, flush=True)
24
+ SH = lambda c: subprocess.run(c, shell=True).returncode
25
+ os.makedirs(W, exist_ok=True)
26
+
27
+ B("EMBEDDED SOURCES -> /kaggle/working")
28
+ SRC_PACK_G256 = r'''import os, json, math, re, types, pickle, random, numpy as np, torch, torch.nn.functional as F
29
+ from transformers import AutoModelForCausalLM, AutoTokenizer
30
+
31
+ SEQ = 512
32
+ MID = "allenai/OLMoE-1B-7B-0125-Instruct"
33
+ OUT = "/kaggle/working/v1_g256"
34
+ os.makedirs(OUT, exist_ok=True)
35
+ torch.manual_seed(0)
36
+ tok = AutoTokenizer.from_pretrained(MID)
37
+ m = AutoModelForCausalLM.from_pretrained(MID, torch_dtype=torch.float16, device_map="auto")
38
+ for p in m.parameters():
39
+ p.requires_grad_(False)
40
+
41
+ mods = {}
42
+ for name, mod in m.named_modules():
43
+ if name.endswith(".mlp.experts"):
44
+ mm = re.search(r"\.layers\.(\d+)\.", name)
45
+ if mm:
46
+ mods[int(mm.group(1))] = mod
47
+ L = sorted(mods)
48
+ hidden, inter = m.config.hidden_size, m.config.intermediate_size
49
+ orig = {(li, nm): getattr(mods[li], nm).data.cpu().clone()
50
+ for li in L for nm in ("gate_up_proj", "down_proj")}
51
+ print("experts:", len(mods), flush=True)
52
+
53
+ MODE = os.environ.get("TRNR_MODE", "gptq")
54
+ print("MODE =", MODE, flush=True)
55
+ ROTF = "/kaggle/working/v1_g256/rotation_H.pt"
56
+ if os.path.exists(ROTF):
57
+ H1 = torch.load(ROTF).float().cpu()
58
+ assert H1.shape == (hidden, hidden), H1.shape
59
+ print("REUSING rotation_H.pt -- rot tensor and router fold stay valid", flush=True)
60
+ else:
61
+ H1, _ = torch.linalg.qr(torch.randn(hidden, hidden, device="cuda:0"))
62
+ H1 = H1.float().cpu()
63
+ print("drew a fresh rotation", flush=True)
64
+ def H1_on(dev):
65
+ return H1.to(dev)
66
+
67
+ # rows come from /tmp/trnr/wiki_rows.pkl (fetched directly from the parquet),
68
+ # NOT from `datasets` -- the transformers/hf_hub upgrade left datasets 4.8.5
69
+ # wanting hf_hub<2.0 while the env has 2.5.0. Same text, no extra dependency.
70
+ ROWS = pickle.load(open("/tmp/trnr/wiki_rows.pkl", "rb"))
71
+
72
+ def get_batches(split, n, shuffle=False):
73
+ rows = list(ROWS[split])
74
+ if shuffle:
75
+ random.Random(7).shuffle(rows)
76
+ need = SEQ * n
77
+ ids, eos = [], tok.eos_token_id
78
+ for t in rows:
79
+ if t.strip():
80
+ ids += tok(t).input_ids
81
+ ids.append(eos)
82
+ if len(ids) >= need:
83
+ break
84
+ T = torch.tensor(ids[:need]).view(-1, SEQ)
85
+ return [T[i].unsqueeze(0).to("cuda:0") for i in range(T.shape[0])]
86
+
87
+ cal_batches = get_batches("train", 64, shuffle=True)
88
+ print("calib chunks:", len(cal_batches), flush=True)
89
+
90
+ ROT = {"on": True}
91
+ CAL_D = {"on": False}
92
+ gate_acc = {li: None for li in L}
93
+ down_acc = {li: [None] * 64 for li in L} # PER-EXPERT
94
+ cntG = {li: 0 for li in L}
95
+ cntD = {li: [0] * 64 for li in L}
96
+
97
+ def fwd(self, hs, top_k_index, top_k_weights):
98
+ final = torch.zeros_like(hs)
99
+ with torch.no_grad():
100
+ em = F.one_hot(top_k_index, num_classes=self.num_experts + 1).permute(2, 1, 0)
101
+ hit = torch.greater(em.sum(dim=(-1, -2)), 0).nonzero()
102
+ gu, dp = self.gate_up_proj, self.down_proj
103
+ Hl = H1_on(hs.device) if ROT["on"] else None
104
+ li = getattr(self, "layer_idx", None)
105
+ for e in hit:
106
+ e = e[0]
107
+ if e == self.num_experts:
108
+ continue
109
+ pos, tk = torch.where(em[e])
110
+ x = hs[tk]
111
+ if Hl is not None:
112
+ x = x @ Hl.to(x.dtype)
113
+ gate, up = F.linear(x, gu[e].to(x.dtype)).chunk(2, dim=-1)
114
+ chs = self.act_fn(gate) * up
115
+ if CAL_D["on"] and li is not None:
116
+ c = chs.float()
117
+ w = top_k_weights[tk, pos].float().reshape(-1, 1) # g_{t,e}, top-8 routing
118
+ assert w.min() >= 0.0 and w.max() <= 1.0, (float(w.min()), float(w.max()))
119
+ if li == L[0] and cntD[li][0] == 0:
120
+ print("gate weights: n=%d mean=%.4f max=%.4f min=%.4f" % (
121
+ w.numel(), float(w.mean()), float(w.max()), float(w.min())), flush=True)
122
+ cw = c * w # loss ~ sum_t g^2 |delta_e|^2
123
+ Hd = (cw.T @ cw).cpu()
124
+ dq = down_acc[li][e]
125
+ down_acc[li][e] = Hd if dq is None else dq + Hd
126
+ cntD[li][e] += c.shape[0]
127
+ chs = F.linear(chs, dp[e].to(chs.dtype))
128
+ chs = chs * top_k_weights[tk, pos, None]
129
+ final.index_add_(0, tk, chs.to(final.dtype))
130
+ return final
131
+
132
+ for li in L:
133
+ mods[li].layer_idx = li
134
+ mods[li].forward = types.MethodType(fwd, mods[li])
135
+
136
+ hooks = []
137
+ def mk(li):
138
+ def h(module, args):
139
+ x = args[0].reshape(-1, args[0].shape[-1]).float()
140
+ Hx = (x.T @ x).cpu()
141
+ gate_acc[li] = Hx if gate_acc[li] is None else gate_acc[li] + Hx
142
+ cntG[li] += x.shape[0]
143
+ return h
144
+ for li in L:
145
+ hooks.append(m.model.layers[li].mlp.register_forward_pre_hook(mk(li)))
146
+ if MODE != "rtn":
147
+ print("calibrating gate Hessian ...", flush=True)
148
+ with torch.no_grad():
149
+ for i in range(len(cal_batches)):
150
+ m(input_ids=cal_batches[i])
151
+ else:
152
+ print("RTN mode: no Hessian needed, skipping calibration", flush=True)
153
+ for h in hooks:
154
+ h.remove()
155
+
156
+ damp = 1e-2
157
+ def robust_U(A, base_damp=damp):
158
+ n = A.shape[0]
159
+ A = 0.5 * (A + A.mT)
160
+ d = torch.diag(A).mean().clamp_min(1e-12)
161
+ for mult in (base_damp, base_damp*10, 0.1, 0.5, 2.0):
162
+ try:
163
+ Hi = torch.linalg.inv(A + mult * d * torch.eye(n))
164
+ return torch.linalg.cholesky(0.5 * (Hi + Hi.mT)).mT
165
+ except Exception:
166
+ continue
167
+ return torch.diag(1.0 / torch.sqrt(torch.diag(A).clamp_min(1e-12)))
168
+
169
+ G = 256
170
+ def rtn_one(W2, g):
171
+ """unweighted LS scale fit, NO error feedback -- the RTN control"""
172
+ rows, n = W2.shape
173
+ Q = torch.empty_like(W2)
174
+ S = torch.zeros(rows, n // g, dtype=torch.float32, device=W2.device)
175
+ for k in range(n // g):
176
+ B = W2[:, k*g:(k+1)*g]
177
+ gam = 2.0 * B.abs().median(dim=1).values.clamp_min(1e-8)
178
+ for _ in range(4):
179
+ Tb = torch.clamp(torch.round(B / gam[:, None]), -1.0, 1.0)
180
+ den = (Tb * Tb).sum(dim=1)
181
+ gam = torch.where(den > 1e-12, (B * Tb).sum(dim=1) / den.clamp_min(1e-12), 0.5 * gam)
182
+ Tb = torch.clamp(torch.round(B / gam[:, None]), -1.0, 1.0)
183
+ Q[:, k*g:(k+1)*g] = gam[:, None] * Tb
184
+ S[:, k] = gam
185
+ return Q, S
186
+
187
+ U_gate = {}
188
+ for li in L:
189
+ if MODE == "rtn":
190
+ break
191
+ Hr = gate_acc[li] / max(cntG[li], 1)
192
+ Hc = H1.float().T @ (Hr + damp * torch.diag(Hr).mean() * torch.eye(hidden)) @ H1.float()
193
+ U_gate[li] = robust_U(Hc)
194
+ gate_acc[li] = None
195
+
196
+ def gptq(W, U, g):
197
+ """canonical GPTQ. returns Q = gamma*t (fp32) and scales S (rows, n//g) fp32"""
198
+ rows, n = W.shape
199
+ U = U.to(W.device)
200
+ Q = torch.empty_like(W)
201
+ S = torch.zeros(rows, n // g, dtype=torch.float32, device=W.device)
202
+ Wl = W.clone()
203
+ for k in range(n // g):
204
+ i0, i1 = k*g, (k+1)*g
205
+ B = Wl[:, i0:i1]
206
+ d = U[i0:i1, i0:i1].diag()
207
+ u = 1.0 / d**2
208
+ gam = 2.0 * B.abs().median(dim=1).values.clamp_min(1e-8)
209
+ for _ in range(4):
210
+ Tb = torch.clamp(torch.round(B / gam[:, None]), -1.0, 1.0)
211
+ num = (B * Tb * u).sum(dim=1)
212
+ den = (Tb * Tb * u).sum(dim=1)
213
+ gam = torch.where(den > 1e-12, num / den, 0.5 * gam)
214
+ Tb = torch.clamp(torch.round(B / gam[:, None]), -1.0, 1.0)
215
+ Qb = gam[:, None] * Tb
216
+ Q[:, i0:i1] = Qb
217
+ S[:, k] = gam
218
+ if i1 < n:
219
+ Wl[:, i1:] -= ((B - Qb) / d[None, :]) @ U[i0:i1, i1:]
220
+ return Q, S
221
+
222
+ blobs = {}
223
+ tot_bytes = [0]; scales_bytes = [0]; numel_tot = [0]; zero_tot = [0]
224
+
225
+ TQB = {}
226
+
227
+
228
+ def encode_digits(dg, sc):
229
+ """TQ1_0 bytes from EXPLICIT digits and scales: GPTQ already chose them, so only
230
+ the byte layout is applied. Layout mirrors gguf-py's TQ1_0 quantizer, which is
231
+ byte-identical to the C (verified), plus the clamp that a sub-absmax scale needs."""
232
+ import numpy as _np
233
+ dg = _np.asarray(dg, _np.int8); sc = _np.asarray(sc, _np.float32)
234
+ nb = dg.shape[0]
235
+ q = (dg + _np.int8(1)).astype(_np.uint8)
236
+ W5 = _np.array([81, 27, 9, 3, 1], _np.uint8)
237
+ W4 = _np.array([81, 27, 9, 3], _np.uint8)
238
+ a = _np.sum(q[:, :160].reshape(nb, -1, 5, 32) * W5.reshape(1, 1, 5, 1), -2).reshape(nb, -1)
239
+ b = _np.sum(q[:, 160:240].reshape(nb, -1, 5, 16) * W5.reshape(1, 1, 5, 1), -2).reshape(nb, -1)
240
+ c = _np.sum(q[:, 240:].reshape(nb, -1, 4, 4) * W4.reshape(1, 1, 4, 1), -2).reshape(nb, -1)
241
+ qq = _np.concatenate([a, b, c], -1)
242
+ qq = ((qq.astype(_np.uint16) * 256 + 242) // 243).astype(_np.uint8)
243
+ sc16 = _np.maximum(sc, 0.0).astype(_np.float16).view(_np.uint8).reshape(nb, 2)
244
+ return _np.concatenate([qq, sc16], -1)
245
+
246
+
247
+ def pack_trits(t):
248
+ pres = (t != 0).to(torch.uint8).flatten().cpu().numpy()
249
+ sign = (t > 0)[t != 0].to(torch.uint8).flatten().cpu().numpy()
250
+ pb = np.packbits(pres); sb = np.packbits(sign)
251
+ p = np.unpackbits(pb)[:t.numel()].astype(bool)
252
+ s = np.unpackbits(sb)[:int(p.sum())].astype(bool)
253
+ rec = np.zeros(t.numel(), np.int8); rec[p] = np.where(s, 1, -1)
254
+ assert np.array_equal(rec.reshape(t.shape), t.cpu().numpy()), "round-trip mismatch"
255
+ return torch.from_numpy(pb.copy()), torch.from_numpy(sb.copy())
256
+
257
+ def record(li, nm, e, Q, S):
258
+ Se = S.repeat_interleave(G, dim=1)
259
+ t = torch.round(Q / Se).to(torch.int8).clamp_(-1, 1)
260
+ pb, sb = pack_trits(t)
261
+ blobs["%d_%s_%d_pres" % (li, nm, e)] = pb
262
+ blobs["%d_%s_%d_sign" % (li, nm, e)] = sb
263
+ blobs["%d_%s_%d_scale" % (li, nm, e)] = S.cpu().half()
264
+ tot_bytes[0] += pb.numel() + sb.numel()
265
+ scales_bytes[0] += S.numel() * 2
266
+ numel_tot[0] += t.numel()
267
+ zero_tot[0] += (t == 0).sum().item()
268
+ # --- also emit TQ1_0 bytes for this expert (worker for the GGUF) ---------
269
+ rows_, n_ = t.shape
270
+ ng = n_ // 256
271
+ if ng * 256 != n_:
272
+ raise RuntimeError("tensor width %d not a multiple of 256" % n_)
273
+ TQB["%d_%s_%d" % (li, nm, e)] = encode_digits(
274
+ t.cpu().numpy().reshape(rows_ * ng, 256), S.cpu().numpy().reshape(rows_ * ng))
275
+
276
+ print("quantizing + packing gate_up ...", flush=True)
277
+ for li in L:
278
+ w = mods[li].gate_up_proj.data
279
+ Hd = H1_on(w.device)
280
+ for e in range(w.shape[0]):
281
+ Wr = w[e].float() @ Hd
282
+ Q, S = (rtn_one(Wr, G) if MODE == "rtn" else gptq(Wr, U_gate[li], G))
283
+ w[e] = Q.to(w.dtype)
284
+ record(li, "gate_up_proj", e, Q, S)
285
+ print(" layer %d gate packed" % li, flush=True)
286
+
287
+ if MODE == "rtn":
288
+ print("RTN: no down Hessian needed, skipping recalibration", flush=True)
289
+ else:
290
+ print("recalibrating down (through quantized gate) ...", flush=True)
291
+ for li in L:
292
+ down_acc[li] = [None] * 64; cntD[li] = [0] * 64
293
+ CAL_D["on"] = True
294
+ with torch.no_grad():
295
+ for i in range(len(cal_batches)):
296
+ m(input_ids=cal_batches[i])
297
+ CAL_D["on"] = False
298
+
299
+ print("quantizing + packing down_proj ...", flush=True)
300
+ for li in L:
301
+ wd = mods[li].down_proj.data
302
+ for e in range(wd.shape[0]):
303
+ if MODE == "rtn":
304
+ Q, S = rtn_one(wd[e].float(), G)
305
+ else:
306
+ U_d = robust_U(down_acc[li][e] / max(cntD[li][e], 1))
307
+ Q, S = gptq(wd[e].float(), U_d, G)
308
+ wd[e] = Q.to(wd.dtype)
309
+ record(li, "down_proj", e, Q, S)
310
+ down_acc[li] = None
311
+ print(" layer %d down packed" % li, flush=True)
312
+
313
+ total = tot_bytes[0] + scales_bytes[0]
314
+ manifest = {
315
+ "base_model": MID,
316
+ "method": "ternary g%d; MODE=%s; dense random rotation; per-expert g^2-weighted down Hessian" % (G, MODE),
317
+ "group_size": G,
318
+ "layers": L,
319
+ "shapes": {"gate_up_proj": [64, 2048, 2048], "down_proj": [64, 2048, 1024]},
320
+ "numel": numel_tot[0],
321
+ "zero_fraction": zero_tot[0] / numel_tot[0],
322
+ "bytes_trits": tot_bytes[0],
323
+ "bytes_scales": scales_bytes[0],
324
+ "bytes_total": total,
325
+ "bits_per_weight": 8.0 * total / numel_tot[0],
326
+ "rotation": "dense orthogonal H (2048x2048); runtime x -> x@H; weights stored as W@H",
327
+ "layout": "per tensor/expert: {presence bitmap, nonzero sign bitmap, fp16 group scales}",
328
+ }
329
+ torch.save(blobs, os.path.join(OUT, "ternary_experts.pt"))
330
+ import pickle
331
+ with open(os.path.join(OUT, "tq1_0_bytes%s.pkl" % ("" if MODE == "gptq" else "_" + MODE)), "wb") as _fh:
332
+ pickle.dump(TQB, _fh)
333
+ print("TQ1_0 packed: %d experts, %d blocks, %.4f GB"
334
+ % (len(TQB), sum(v.shape[0] for v in TQB.values()),
335
+ sum(v.nbytes for v in TQB.values()) / 1e9))
336
+ torch.save(H1, os.path.join(OUT, "rotation_H.pt"))
337
+ with open(os.path.join(OUT, "manifest.json"), "w") as f:
338
+ json.dump(manifest, f, indent=2)
339
+
340
+ print("\n=== V1 ARTIFACT ===")
341
+ print("params : %.3f B" % (numel_tot[0] / 1e9))
342
+ print("zero fraction : %.1f%%" % (100 * manifest["zero_fraction"]))
343
+ print("trit blobs : %.3f GB" % (tot_bytes[0] / 1e9))
344
+ print("scales : %.3f GB" % (scales_bytes[0] / 1e9))
345
+ print("TOTAL : %.3f GB" % (total / 1e9))
346
+ print("bits/weight : %.3f" % manifest["bits_per_weight"])
347
+ print("files :", sorted(os.listdir(OUT)))
348
+
349
+
350
+ '''
351
+ SRC_TRNR_CONVERT = r'''#!/usr/bin/env python3
352
+ """
353
+ trnr / stage-1b converter -- rotate + fold, NO quantization.
354
+
355
+ Purpose
356
+ -------
357
+ Produce the FIRST trnr GGUF and use it for the one test that isolates the whole
358
+ rotation machinery:
359
+
360
+ rotated-but-unquantized MUST reproduce stock perplexity exactly.
361
+
362
+ Because D/H rotation is orthogonal, storing W@R and applying x@R changes nothing
363
+ mathematically. So if the ppl does not match stock, the failure is one of exactly
364
+ four things -- tensor orientation, the router fold, the graph line's position, or
365
+ the layer-type registration -- each with a distinct signature. That is a far better
366
+ debugging position than a quantized number where all four plus the quantization are
367
+ tangled together.
368
+
369
+ What it does
370
+ ------------
371
+ Monkeypatches conversion.olmo.OlmoeModel.modify_tensors rather than subclassing:
372
+ avoids all registry plumbing, and the converter's own OlmoeModel already fuses the
373
+ per-expert checkpoint tensors into 3-D [E, ...] tensors for us.
374
+
375
+ blk.N.ffn_gate_exps.weight (torch [E, I, hidden]) -> @ R on the input dim
376
+ blk.N.ffn_up_exps.weight (torch [E, I, hidden]) -> @ R on the input dim
377
+ blk.N.ffn_down_exps.weight (torch [E, hidden, I]) -> UNCHANGED (down is not rotated)
378
+ blk.N.ffn_gate_inp.weight (torch [64, hidden]) -> @ R (router fold)
379
+ + one extra tensor trnr.rot = R itself, ne = (hidden, hidden)
380
+
381
+ Orientation, derived from the ggml index convention (and verified numerically:
382
+ the rotation cancels to 3.9e-14):
383
+ a stored 2-D weight of torch shape [out, in] is written with ne=(in, out)
384
+ runtime build_lora_mm(A, x) = x @ A_TORCH (A_TORCH = [out, in] = the array.T)
385
+ so x -> x@R needs array = R, and W -> W@R needs array = (W@R).T
386
+ router: W_r' = W_r @ R, written as (W_r @ R).T
387
+ 3-D expert tensors use ne=(in, out, E), i.e. torch [E, out, in].permute(2,1,0)
388
+
389
+ CRITICAL import detail: llama.cpp's bundled gguf-py MUST win over any pip-installed
390
+ `gguf`, or ~70 conversion modules fail to import (MODEL_TENSOR missing members).
391
+ convert_hf_to_gguf.py does this itself; we are a separate entry point, so we do it
392
+ too, and in a fresh interpreter.
393
+ """
394
+ import os
395
+ import sys
396
+ import runpy
397
+
398
+ SRC = "/tmp/trnr/llama.cpp"
399
+ sys.path.insert(0, SRC)
400
+ sys.path.insert(1, os.path.join(SRC, "gguf-py")) # local gguf must win
401
+ os.environ.pop("NO_LOCAL_GGUF", None)
402
+ for m in [k for k in list(sys.modules) if k == "gguf" or k.startswith("gguf.")]:
403
+ del sys.modules[m]
404
+
405
+ import torch
406
+ import gguf
407
+ from conversion.olmo import OlmoeModel
408
+
409
+ assert "llama.cpp/gguf-py" in gguf.__file__, \
410
+ "wrong gguf: %s (local gguf-py did not win)" % gguf.__file__
411
+
412
+ ROT_PATH = sys.argv[sys.argv.index("--rot") + 1]
413
+ # keep a real argv[0]: sys.argv[1:] alone would put the checkpoint path at index 0,
414
+ # where argparse treats it as the PROGRAM NAME and then reports "model is required".
415
+ argv = [sys.argv[0]] + [a for a in sys.argv[1:] if a not in ("--rot", ROT_PATH)]
416
+ print("[trnr] argv -> %s" % " ".join(argv), flush=True)
417
+
418
+ R = torch.load(ROT_PATH, map_location="cpu").float()
419
+ assert R.shape[0] == R.shape[1], R.shape
420
+ HID = R.shape[0]
421
+ print("[trnr] rotation R: %s (dense orthogonal)" % (tuple(R.shape),), flush=True)
422
+ print("[trnr] orthogonal check ||R R^T - I||_max = %.3e"
423
+ % (R @ R.T - torch.eye(HID)).abs().max(), flush=True)
424
+
425
+ _orig = OlmoeModel.modify_tensors
426
+ STATS = {"gate": 0, "up": 0, "down": 0, "router": 0, "rot": 0}
427
+
428
+
429
+ def _trnr_emitted(self):
430
+ return getattr(self, "_trnr_rot_done", False)
431
+
432
+
433
+ def _trnr_mark(self):
434
+ self._trnr_rot_done = True
435
+
436
+
437
+ def patched(self, data_torch, name, bid):
438
+ for new_name, t in _orig(self, data_torch, name, bid):
439
+ out_name, out_t = new_name, t
440
+
441
+ if new_name.endswith("ffn_gate_exps.weight") or new_name.endswith("ffn_up_exps.weight"):
442
+ # torch [E, out, in] -> rotate the INPUT (last) dim
443
+ assert t.shape[-1] == HID, (new_name, t.shape)
444
+ out_t = (t.float() @ R).to(t.dtype)
445
+ STATS["gate" if "gate" in new_name else "up"] += 1
446
+
447
+ elif new_name.endswith("ffn_down_exps.weight"):
448
+ STATS["down"] += 1 # deliberately untouched
449
+
450
+ elif new_name.endswith("ffn_gate_inp.weight"):
451
+ # gguf ne=(hidden, 64) -> torch [64, hidden]; fold R on the input dim
452
+ assert t.shape[-1] == HID, (new_name, t.shape)
453
+ out_t = (t.float() @ R).to(t.dtype)
454
+ STATS["router"] += 1
455
+
456
+ yield out_name, out_t
457
+
458
+ # the rotation tensor itself, once, on first expert contact
459
+ if (not _trnr_emitted(self)) and new_name.endswith("ffn_gate_exps.weight"):
460
+ _trnr_mark(self)
461
+ STATS["rot"] += 1
462
+ # gguf ne=(hidden, hidden); array = R (see orientation derivation)
463
+ # MUST be a torch tensor: prepare_tensors() calls .numpy() on every tensor,
464
+ # and a numpy array there raises "ndarray has no attribute numpy"
465
+ # name MUST carry the .weight suffix: llama.cpp matches against
466
+ # <stem>.weight (the arch table holds the stem "trnr.rot"), and an
467
+ # unsuffixed name is skipped -> "expected 196, got 195"
468
+ # R.T, not R: gguf-py stores ne=reversed(torch_shape) as a real permute, so a
469
+ # 2-D tensor is stored TRANSPOSED; and the runtime map is T = S, while the
470
+ # experts need E*T = W with E = W*R => T = R^T => S = R^T.
471
+ yield "trnr.rot.weight", R.T.to(torch.float32).contiguous()
472
+
473
+
474
+ OlmoeModel.modify_tensors = patched
475
+
476
+ print("[trnr] monkeypatched OlmoeModel.modify_tensors; running stock converter", flush=True)
477
+ sys.argv = argv
478
+ _rc = 0
479
+ try:
480
+ runpy.run_path(os.path.join(SRC, "convert_hf_to_gguf.py"), run_name="__main__")
481
+ finally:
482
+ print("\n[trnr] transform counts: %s" % STATS, flush=True)
483
+ print("[trnr] expected per layer: gate 16, up 16, down 16, router 16, rot 1", flush=True)
484
+ '''
485
+ SRC_APPLY_STAGE1 = r'''#!/usr/bin/env python3
486
+ """
487
+ trnr.cpp · STAGE 1 patcher -- wire the expert-input rotation into OLMoE.
488
+
489
+ Design
490
+ ------
491
+ Anchor-based, indentation-agnostic, FAIL-LOUD. Every edit names an exact
492
+ expected snippet; if the snippet is missing or ambiguous the script aborts
493
+ BEFORE writing anything and says which anchor moved. Anchors are matched with
494
+ leading whitespace wildcarded and the replacement is re-indented to whatever
495
+ indent the matched line actually has, so an upstream reformat or rebase does not
496
+ silently produce a wrong patch.
497
+
498
+ The rotation is deliberately minimal:
499
+
500
+ * ONE new ggml tensor, "trnr.rot", held on llama_model_base -- NOT on
501
+ llama_model_olmoe. llm_graph_context::model is base-typed (it is one class
502
+ shared by every architecture), so a derived-class member would not compile.
503
+ * ONE new line in the OLMoE graph, between ffn_norm and build_moe_ffn:
504
+ cur = build_lora_mm(model.trnr_rot, cur);
505
+ * build_moe_ffn is NOT touched. The router weights are pre-multiplied by H at
506
+ conversion time (G = (W_router @ H)^T), so the router still sees exactly the
507
+ logits it would have seen on the unrotated input: H is orthogonal, so
508
+ W_router' (x H) = W_router x.
509
+
510
+ Everything is optional: with no "trnr.rot" tensor in the GGUF the model loads
511
+ and behaves exactly like stock OLMoE.
512
+
513
+ NOTE: lines given to the ("after", ...) ops are RELATIVE (no leading indent);
514
+ the patcher re-indents them to the anchor line's indentation.
515
+ """
516
+ import argparse
517
+ import difflib
518
+ import os
519
+ import re
520
+ import sys
521
+
522
+ # ---------------------------------------------------------------------------
523
+ # edits
524
+ # ---------------------------------------------------------------------------
525
+ OPS = [
526
+ # -- the one graph line: rotate the expert input ----------------------
527
+ ("replace", "src/models/olmoe.cpp",
528
+ ' cb(cur, "ffn_norm", il);\n'
529
+ '\n'
530
+ ' cur = build_moe_ffn(cur,',
531
+ ' cb(cur, "ffn_norm", il);\n'
532
+ '\n'
533
+ ' // trnr.cpp: rotate the expert input into the quantization basis.\n'
534
+ ' // The router weights were pre-multiplied by H at conversion time, so the\n'
535
+ ' // router still produces exactly the logits it would on the raw input.\n'
536
+ ' if (model.trnr_rot != nullptr) {\n'
537
+ ' cur = build_lora_mm(model.trnr_rot, cur);\n'
538
+ ' cb(cur, "trnr_rot", il);\n'
539
+ ' }\n'
540
+ '\n'
541
+ ' cur = build_moe_ffn(cur,'),
542
+
543
+ # -- load it (optional: absent from stock models) ---------------------
544
+ ("after", "src/models/olmoe.cpp",
545
+ 'output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);',
546
+ ['',
547
+ '// trnr.cpp: input rotation for ternary expert weights. Absent from stock',
548
+ '// models, so it is optional and the graph is a no-op without it.',
549
+ 'trnr_rot = create_tensor(tn(LLM_TENSOR_TRNR_ROT, "weight"), {n_embd, n_embd}, TENSOR_NOT_REQUIRED);']),
550
+
551
+ # -- register the tensor ---------------------------------------------
552
+ ("after", "src/llama-arch.h",
553
+ "LLM_TENSOR_OUTPUT_NORM_LFM2, // fix for wrong tensor name",
554
+ ["LLM_TENSOR_TRNR_ROT, // trnr.cpp: expert-input rotation"]),
555
+
556
+ ("after", "src/llama-arch.cpp",
557
+ '{ LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },',
558
+ ['{ LLM_TENSOR_TRNR_ROT, "trnr.rot" },']),
559
+
560
+ ("after", "src/llama-arch.cpp",
561
+ "{LLM_TENSOR_FFN_UP_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},",
562
+ ["{LLM_TENSOR_TRNR_ROT, {LLM_TENSOR_LAYER_INPUT, GGML_OP_MUL_MAT}},"]),
563
+ ]
564
+
565
+ # tok_embd is a member of llama_model_base and we do not know which header holds
566
+ # it, so we find the declaration at runtime.
567
+ DYN_MEMBER_ANCHOR = "tok_embd"
568
+ DYN_MEMBER_LINE = "struct ggml_tensor * trnr_rot = nullptr; // trnr.cpp: expert input rotation"
569
+
570
+ # the one judgement call, flagged on purpose:
571
+ # LLM_TENSOR_LAYER_INPUT = created once (like token_embd), used with MUL_MAT.
572
+ # If the loader refuses it, switch to LLM_TENSOR_LAYER_OUTPUT (like output).
573
+ TENSOR_LAYER = "LLM_TENSOR_LAYER_INPUT"
574
+
575
+
576
+ # ---------------------------------------------------------------------------
577
+ def read(path):
578
+ with open(path, encoding="utf-8") as f:
579
+ return f.read()
580
+
581
+
582
+ def leading_ws(line):
583
+ return re.match(r"[ \t]*", line).group(0)
584
+
585
+
586
+ def norm_block(text):
587
+ """split into lines and remove the first line's indent from all of them"""
588
+ lines = text.split("\n")
589
+ base = leading_ws(lines[0])
590
+ return [l[len(base):] if l.startswith(base) else l.lstrip() for l in lines]
591
+
592
+
593
+ def flex_regex(rel_lines):
594
+ parts = []
595
+ for l in rel_lines:
596
+ parts.append(r"[ \t]*" if l.strip() == "" else r"[ \t]*" + re.escape(l))
597
+ return re.compile("\n".join(parts))
598
+
599
+
600
+ def reindent(rel_lines, indent):
601
+ return "\n".join((indent + l) if l.strip() else "" for l in rel_lines)
602
+
603
+
604
+ def find_member_decls(src, needle):
605
+ """Find the member declaration of `needle` on a model struct.
606
+
607
+ Must not match function declarations that merely take `needle` as a
608
+ parameter -- llama-graph.h has
609
+ ggml_tensor * build_inp_embd(ggml_tensor * tok_embd, float tok_scale = 1.0f) const;
610
+ which also ends in ';'. Excluding lines containing '(' leaves only the real
611
+ member, e.g. llama-model.h:
612
+ struct ggml_tensor * tok_embd = nullptr;
613
+ """
614
+ hits = []
615
+ for root, _, files in os.walk(os.path.join(src, "src")):
616
+ for fn in sorted(files):
617
+ if not fn.endswith(".h"):
618
+ continue
619
+ p = os.path.join(root, fn)
620
+ for i, line in enumerate(read(p).splitlines()):
621
+ if (re.search(r"\b%s\b" % re.escape(needle), line)
622
+ and "(" not in line
623
+ and line.rstrip().endswith(";")):
624
+ hits.append((p, i, line))
625
+ return hits
626
+
627
+
628
+ # ---------------------------------------------------------------------------
629
+ def main():
630
+ ap = argparse.ArgumentParser()
631
+ ap.add_argument("--src", default="/tmp/trnr/llama.cpp")
632
+ ap.add_argument("--apply", action="store_true", help="write changes (default: dry run)")
633
+ a = ap.parse_args()
634
+
635
+ if not os.path.isdir(a.src):
636
+ sys.exit("no such source tree: %s" % a.src)
637
+
638
+ # ---- 0. preflight ----------------------------------------------------
639
+ chunks = []
640
+ for root, _, files in os.walk(os.path.join(a.src, "src")):
641
+ for fn in files:
642
+ if fn.endswith((".h", ".cpp")):
643
+ chunks.append(read(os.path.join(root, fn)))
644
+ grep = "".join(chunks)
645
+ for token in ("TENSOR_NOT_REQUIRED", "build_lora_mm", "create_tensor"):
646
+ if token not in grep:
647
+ print(" !! WARNING: %r not found in src/ -- patch may not compile" % token)
648
+ ggml_h = read(os.path.join(a.src, "ggml/include/ggml.h"))
649
+ m = re.search(r"GGML_TYPE_F8_E4M3\s*=\s*(\d+)", ggml_h)
650
+ if m and int(m.group(1)) == 43:
651
+ print(" [ok] ggml.h enum still ends at F8_E4M3 = 43 (stage 2 will take 44)")
652
+ else:
653
+ print(" !! WARNING: ggml.h type enum changed -- recheck the stage-2 type number")
654
+
655
+ # ---- 1. resolve the dynamic member insertion on llama_model_base -----
656
+ decls = find_member_decls(a.src, DYN_MEMBER_ANCHOR)
657
+ print("\n[%r declarations found: %d]" % (DYN_MEMBER_ANCHOR, len(decls)))
658
+ for p, i, line in decls:
659
+ print(" %s:%d %s" % (p.replace(a.src, ""), i + 1, line.strip()))
660
+ if len(decls) != 1:
661
+ sys.exit("ABORT: expected exactly 1 %r declaration, got %d. Which one is "
662
+ "llama_model_base?" % (DYN_MEMBER_ANCHOR, len(decls)))
663
+ mpath, _, mtext = decls[0]
664
+
665
+ ops = list(OPS) + [("after", os.path.relpath(mpath, a.src), mtext.strip(),
666
+ [DYN_MEMBER_LINE])]
667
+
668
+ # ---- 2. plan every edit; abort if any anchor is not unique ----------
669
+ touched = {}
670
+ failures = []
671
+ plan = []
672
+ for op in ops:
673
+ kind, rel, anchor, payload = op
674
+ path = os.path.join(a.src, rel)
675
+ if not os.path.exists(path):
676
+ failures.append("missing file %s" % rel)
677
+ continue
678
+ cur = touched.get(path, read(path))
679
+
680
+ if kind == "replace":
681
+ rx = flex_regex(norm_block(anchor))
682
+ ms = list(rx.finditer(cur))
683
+ if len(ms) != 1:
684
+ failures.append("%s: anchor matched %d times (want 1): %r"
685
+ % (rel, len(ms), anchor[:70]))
686
+ continue
687
+ mm = ms[0]
688
+ # the regex leads each line with [ \t]*, so the match BEGINS at the
689
+ # indentation; read the indent from the matched text, not the gap
690
+ # before it (that gap is always empty).
691
+ indent = leading_ws(cur[mm.start():])
692
+ repl = reindent(norm_block(payload), indent)
693
+ touched[path] = cur[:mm.start()] + repl + cur[mm.end():]
694
+ plan.append((rel, indent, anchor, repl, True))
695
+ else: # after
696
+ lines = cur.splitlines(keepends=True)
697
+ idx = [i for i, l in enumerate(lines) if anchor in l]
698
+ if len(idx) != 1:
699
+ failures.append("%s: anchor matched %d times (want 1): %r"
700
+ % (rel, len(idx), anchor[:70]))
701
+ continue
702
+ at = idx[0]
703
+ indent = leading_ws(lines[at])
704
+ ins = reindent(payload, indent) + "\n"
705
+ lines.insert(at + 1, ins)
706
+ touched[path] = "".join(lines)
707
+ plan.append((rel, indent, anchor, ins, False))
708
+
709
+ if failures:
710
+ print("\nABORT -- %d anchor(s) did not match:" % len(failures))
711
+ for f in failures:
712
+ print(" " + f)
713
+ sys.exit(1)
714
+
715
+ # ---- 3. show the diff ------------------------------------------------
716
+ print("\n" + "=" * 78)
717
+ print("PLANNED CHANGES (%d file(s))" % len(touched))
718
+ print("=" * 78)
719
+ for rel, indent, anchor, repl, is_repl in plan:
720
+ print("\n--- %s (indent=%d spaces)" % (rel, len(indent)))
721
+ if is_repl:
722
+ for l in difflib.unified_diff(anchor.split("\n"), repl.split("\n"),
723
+ lineterm="", n=1):
724
+ print(" " + l)
725
+ else:
726
+ for l in repl.rstrip("\n").split("\n"):
727
+ print(" + " + l)
728
+
729
+ if not a.apply:
730
+ print("\n(dry run -- re-run with --apply to write)")
731
+ return
732
+
733
+ for p, txt in touched.items():
734
+ with open(p, "w", encoding="utf-8") as f:
735
+ f.write(txt)
736
+ print("\nAPPLIED to %d file(s)." % len(touched))
737
+
738
+ # ---- 4. verify -------------------------------------------------------
739
+ print("\nverification:")
740
+ checks = [
741
+ ("src/models/olmoe.cpp", "build_lora_mm(model.trnr_rot, cur)"),
742
+ ("src/models/olmoe.cpp", 'LLM_TENSOR_TRNR_ROT, "weight"'),
743
+ ("src/llama-arch.h", "LLM_TENSOR_TRNR_ROT,"),
744
+ ("src/llama-arch.cpp", '"trnr.rot"'),
745
+ ("src/llama-arch.cpp", "{LLM_TENSOR_TRNR_ROT,"),
746
+ (os.path.relpath(mpath, a.src), "trnr_rot = nullptr"),
747
+ ]
748
+ ok = True
749
+ for rel, needle in checks:
750
+ good = needle in read(os.path.join(a.src, rel))
751
+ ok &= good
752
+ print(" %-4s %s :: %s" % ("OK" if good else "FAIL", rel, needle))
753
+ print("\n%s" % ("PATCH LOOKS COMPLETE" if ok else "PATCH INCOMPLETE"))
754
+ print("tensor layer type used: %s" % TENSOR_LAYER)
755
+
756
+
757
+ if __name__ == "__main__":
758
+ main()
759
+ '''
760
+ SRC_MODEL_CARD = r'''---
761
+ license: apache-2.0
762
+ base_model: allenai/OLMoE-1B-7B-0125-Instruct
763
+ library_name: llama.cpp
764
+ tags: [mixture-of-experts, ternary, quantization, llama.cpp, tq1_0]
765
+ ---
766
+ # trnr: OLMoE-1B-7B-0125-Instruct, expert weights at 1.6875 bits/weight
767
+
768
+ Post-training ternarization of the **expert weights only**: values in {-1, 0, +1} times one fp16
769
+ scale per 256 input columns, packed into llama.cpp's existing **TQ1_0** type. Attention,
770
+ embeddings, the output head and the router stay F16.
771
+
772
+ | | |
773
+ |---|---|
774
+ | expert weights | 1.359 GB at 1.6875 bits/weight, 46% exact zeros |
775
+ | full file | __SIZE__ GB |
776
+ | perplexity | __PPL__ (wikitext-2-raw, 8 x 512 tokens) |
777
+ | fp16 reference | 9.1512, same protocol and same pinned build |
778
+ | ratio | __RATIO__x |
779
+ | speed | ~16 tok/s on 4 CPU threads, no GPU, no custom kernels |
780
+
781
+ ## Method
782
+ 1. One dense random orthogonal rotation R, shared by all 16 layers, applied to the gate_up
783
+ **input** only, with the router folded by the same R so routing is unchanged.
784
+ 2. A per-256-block ternary scale fitted by a Hessian-weighted least-squares objective.
785
+ 3. Canonical GPTQ error feedback across blocks, with a per-expert Hessian for down_proj.
786
+ 4. Bytes packed into TQ1_0's layout, verified byte-identical to llama.cpp's own encoder.
787
+
788
+ ## Requirements
789
+ Needs the companion fork **trnr.cpp** -- one commit over llama.cpp at __PIN8__ -- for the
790
+ rotation tensor. `trnr_rot.patch` is in this repo. Without it the model loads and produces
791
+ garbage.
792
+
793
+ ## Honest limitations
794
+ - __RATIO__x fp16 perplexity, and that is the price of ternary itself: the scalar three-level
795
+ optimum for Gaussian weights is 0.1903 NMSE and this pipeline measures 0.1954, i.e. it is
796
+ **at the optimum for this alphabet**. The remaining gap is ternary, not the fitting.
797
+ - Perplexity is not quality. Downstream tasks degrade more than wikitext suggests.
798
+ - No fine-tuning was used.
799
+ - llama.cpp's stock TQ1_0 quantizer is unusable for this model: its absmax scale sends ~92% of
800
+ weights to zero and yields ppl 5178. The learned per-block scale is what makes the format work.
801
+ '''
802
+ for name, text in (("pack_g256.py", SRC_PACK_G256), ("trnr_convert.py", SRC_TRNR_CONVERT),
803
+ ("apply_stage1.py", SRC_APPLY_STAGE1), ("card.md", SRC_MODEL_CARD)):
804
+ open(os.path.join(K, name), "w").write(text)
805
+ if name.endswith(".py"):
806
+ ast.parse(text)
807
+ P("%-20s %6.1f KB written%s" % (name, len(text) / 1024, " and parses" if name.endswith(".py") else ""))
808
+
809
+ import ast
810
+ import os, re, sys, json, shutil, pickle, tarfile, subprocess
811
+ import numpy as np
812
+ W = "/tmp/trnr"; SRC = W + "/llama.cpp"; K = "/kaggle/working"
813
+ PIN = "16f090f92c0e2ac6dfddcaf93589a9b158c598c7"
814
+ MID = "allenai/OLMoE-1B-7B-0125-Instruct"
815
+ HF_TOKEN = "__HF_TOKEN__" # injected by the runner cell; a real token here makes
816
+ # HuggingFace REJECT the upload (its secret scanner).
817
+ REPO_NAME = "OLMoE-1B-7B-0125-Instruct-ternary-tq1_0"
818
+ B = lambda t: print("=" * 70 + "\n" + t + "\n" + "=" * 70, flush=True)
819
+ P = lambda s: print(" " + s, flush=True)
820
+ SH = lambda c: subprocess.run(c, shell=True).returncode
821
+ os.makedirs(W, exist_ok=True)
822
+
823
+ B("0/8 stage the uploaded source files")
824
+ STAGE = {"UPLOAD_1_pack_g256.py": "pack_g256.py", "UPLOAD_2_trnr_convert.py": "trnr_convert.py",
825
+ "UPLOAD_3_apply_stage1.py": "apply_stage1.py", "UPLOAD_4_model_card.md": "card.md"}
826
+ for up, want in STAGE.items():
827
+ if not os.path.exists(K + "/" + want):
828
+ shutil.copyfile(K + "/" + up, K + "/" + want)
829
+ P("%-22s %.1f KB" % (want, os.path.getsize(K + "/" + want) / 1024))
830
+ for f in ("pack_g256.py", "trnr_convert.py", "apply_stage1.py"):
831
+ ast.parse(open(K + "/" + f).read())
832
+
833
+ B("1/8 clone llama.cpp @ pin")
834
+ if not os.path.isdir(SRC + "/src"):
835
+ assert SH("git init -q %s && cd %s && git remote add origin https://github.com/ggml-org/llama.cpp.git "
836
+ "&& git fetch -q --depth 1 origin %s && git checkout -q FETCH_HEAD" % (SRC, SRC, PIN)) == 0
837
+ P("at %s" % subprocess.run("cd %s && git rev-parse --short HEAD" % SRC, shell=True,
838
+ capture_output=True, text=True).stdout.strip())
839
+
840
+ B("2/8 apply the verified rotation patch (CELL UPLOAD_3) and save it as a diff")
841
+ if "build_lora_mm(model.trnr_rot" not in open(SRC + "/src/models/olmoe.cpp").read():
842
+ assert SH("cd %s && python -u %s --src %s --apply" % (K, K + "/apply_stage1.py", SRC)) == 0, "patch failed"
843
+ SH("cd %s && git add -A && git diff --cached > %s/trnr_rot.patch" % (SRC, K))
844
+ P("trnr_rot.patch %.1f KB" % (os.path.getsize(K + "/trnr_rot.patch") / 1024))
845
+
846
+ B("3/8 data: HF checkpoint + wikitext-2-raw as calibration rows")
847
+ from huggingface_hub import snapshot_download
848
+ HF = snapshot_download(MID, allow_patterns=["*.json", "*.safetensors"])
849
+ P("checkpoint %.1f GB" % (sum(os.path.getsize(os.path.join(HF, f)) for f in os.listdir(HF)) / 1e9))
850
+ if not os.path.exists(K + "/wiki_rows.pkl"):
851
+ SH("cd %s && curl -sSL -o wt2.zip https://huggingface.co/datasets/ggml-org/ci/resolve/main/"
852
+ "wikitext-2-raw-v1.zip && unzip -o -q wt2.zip" % W)
853
+ F = lambda n: subprocess.run("find %s -name '%s' | head -1" % (W, n), shell=True,
854
+ capture_output=True, text=True).stdout.strip()
855
+ tr, te = F("wiki.train.raw"), F("wiki.test.raw")
856
+ assert tr and te, "wikitext fetch failed"
857
+ ROWS = {"train": [l for l in open(tr).read().split("\n") if l.strip()],
858
+ "test": [l for l in open(te).read().split("\n") if l.strip()]}
859
+ for _p in (K + "/wiki_rows.pkl", W + "/wiki_rows.pkl"): # pipeline reads it from /tmp/trnr
860
+ pickle.dump(ROWS, open(_p, "wb"))
861
+ shutil.copyfile(te, K + "/wiki.test.txt")
862
+ P("wiki_rows.pkl + wiki.test.txt ok")
863
+
864
+ B("4/8 quantizer (~9 min, GPU) then converter -> rotated base GGUF")
865
+ assert SH("cd %s && python -u %s" % (K, K + "/pack_g256.py")) == 0, "pipeline failed -- paste this back"
866
+ for f in ("tq1_0_bytes.pkl", "rotation_H.pt"):
867
+ P("%-16s %.4f GB" % (f, os.path.getsize(K + "/v1_g256/" + f) / 1e9))
868
+ BASE = K + "/trnr-base.gguf"
869
+ assert SH("cd %s && python -u %s %s --outtype f16 --outfile %s --rot %s/v1_g256/rotation_H.pt"
870
+ % (K, K + "/trnr_convert.py", HF, BASE, K)) == 0, "conversion failed -- paste this back"
871
+ P("trnr-base.gguf %.3f GB" % (os.path.getsize(BASE) / 1e9))
872
+
873
+ B("5/8 build the patched runtime (~5 min), splice, validate")
874
+ sys.path.insert(0, SRC + "/gguf-py"); import gguf
875
+ PP = SRC + "/build/bin/llama-perplexity"
876
+ if not os.path.isfile(PP):
877
+ assert SH("cd %s && cmake -B build -DCMAKE_BUILD_TYPE=Release -DLLAMA_CURL=OFF -DGGML_CUDA=OFF "
878
+ "-DGGML_CCACHE=OFF >/dev/null 2>&1 && cmake --build build --config Release -j "
879
+ "--target llama-perplexity 2>&1" % SRC) == 0, "build failed"
880
+ DST = K + "/trnr-OLMoE-1B-7B-ternary-tq1_0.gguf"
881
+ TQB = pickle.load(open(K + "/v1_g256/tq1_0_bytes.pkl", "rb"))
882
+ by = {t.name: t for t in gguf.GGUFReader(BASE).tensors}
883
+ off = lambda t: int(np.asarray(t.data_offset).reshape(-1)[0])
884
+ def peek(p, o):
885
+ with open(p, "rb") as fh:
886
+ fh.seek(o); return fh.read(64)
887
+ if not os.path.exists(DST): shutil.copyfile(BASE, DST)
888
+ f = open(DST, "r+b"); nb = 0
889
+ for L in range(16):
890
+ for nm, sl, key in (("ffn_gate_exps", slice(0, 8192), "gate_up_proj"),
891
+ ("ffn_up_exps", slice(8192, 16384), "gate_up_proj"), ("ffn_down_exps", None, "down_proj")):
892
+ buf = np.stack([np.asarray(TQB["%d_%s_%d" % (L, key, e)])[sl] for e in range(64)]).reshape(-1, 54)
893
+ k = "blk.%d.%s.weight" % (L, nm); t = by[k]; o = off(t)
894
+ assert t.data.nbytes == buf.nbytes and peek(DST, o) == np.asarray(t.data).reshape(-1).tobytes()[:64], k
895
+ f.seek(o); f.write(buf.tobytes()); nb += buf.nbytes
896
+ f.close()
897
+ P("spliced %.4f GB -> %.3f GB" % (nb / 1e9, os.path.getsize(DST) / 1e9))
898
+ r = subprocess.run([PP, "-m", DST, "-f", K + "/wiki.test.txt", "-c", "512", "--chunks", "8", "-ngl", "0"],
899
+ capture_output=True, text=True)
900
+ txt = (r.stdout or "") + (r.stderr or "")
901
+ for l in txt.splitlines()[-4:]: P(l[:150])
902
+ g = re.findall(r"Final estimate: PPL = ([0-9.]+)", txt)
903
+ ppl = float(g[-1]) if g else float("nan")
904
+ F16 = 9.1512
905
+ ratio = ppl / F16 if ppl == ppl else float("nan")
906
+ P("ppl %.4f ratio vs f16 %.4f = %.3fx" % (ppl, F16, ratio))
907
+
908
+ B("6/8 model card from the template + upload to HuggingFace")
909
+ card = (open(K + "/card.md").read().replace("__SIZE__", "%.3f" % (os.path.getsize(DST) / 1e9))
910
+ .replace("__PPL__", "%.4f" % ppl).replace("__RATIO__", "%.2f" % ratio).replace("__PIN8__", PIN[:8]))
911
+ open(K + "/README.md", "w").write(card)
912
+ from huggingface_hub import whoami, create_repo, upload_file
913
+ me = whoami(token=HF_TOKEN)["name"]; REPO = "%s/%s" % (me, REPO_NAME)
914
+ P("account %s -> %s" % (me, REPO))
915
+ create_repo(REPO, token=HF_TOKEN, exist_ok=True, repo_type="model")
916
+ for src, dst in ((DST, os.path.basename(DST)), (K + "/README.md", "README.md"),
917
+ (K + "/trnr_rot.patch", "trnr_rot.patch"), (K + "/v1_g256/rotation_H.pt", "rotation_H.pt"),
918
+ (K + "/v1_g256/manifest.json", "manifest.json"), (K + "/pack_g256.py", "pack_g256.py"),
919
+ (K + "/trnr_convert.py", "trnr_convert.py"), (K + "/card.md", None)):
920
+ if dst is None: continue
921
+ upload_file(path_or_fileobj=src, path_in_repo=dst, repo_id=REPO, token=HF_TOKEN)
922
+ P("uploaded %s (%.3f GB)" % (dst, os.path.getsize(src) / 1e9))
923
+ P("https://huggingface.co/%s" % REPO)
924
+
925
+ B("7/8 package the fork as trnr.cpp")
926
+ FORK = K + "/trnr.cpp"
927
+ if not os.path.isdir(FORK):
928
+ shutil.copytree(SRC, FORK, ignore=shutil.ignore_patterns(".git", "build", "*.o", "*.a", "*.so"))
929
+ shutil.copy(K + "/trnr_rot.patch", FORK + "/trnr_rot.patch")
930
+ open(FORK + "/TRNR.md", "w").write(
931
+ "# trnr.cpp\n\nllama.cpp at %s plus ONE commit, `trnr_rot.patch`: a `trnr.rot` ggml tensor\n"
932
+ "and one graph line in `src/models/olmoe.cpp` so the expert-input rotation used by trnr\n"
933
+ "models is applied at runtime. Everything else is upstream.\n\n## Or, cleaner: apply it to\n"
934
+ "a fresh clone (4 KB instead of a 20 MB tree)\n```\ngit clone "
935
+ "https://github.com/ggml-org/llama.cpp\ncd llama.cpp\ngit checkout %s\n"
936
+ "git apply trnr_rot.patch\n```\n" % (PIN[:8], PIN))
937
+ with tarfile.open(K + "/trnr.cpp.tar.gz", "w:gz") as t: t.add(FORK, arcname="trnr.cpp")
938
+ P("fork: trnr.cpp.tar.gz %.1f MB, or just trnr_rot.patch (%.1f KB)"
939
+ % (os.path.getsize(K + "/trnr.cpp.tar.gz") / 1e6, os.path.getsize(K + "/trnr_rot.patch") / 1024))
940
+
941
+ B("8/8 DONE -- ROTATE THE HF TOKEN NOW: huggingface.co/settings/tokens")