omega-helix
This project has not described itself yet.
Brought by drakestapleton
omega-helix / tests / test_interchange.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 |
| 3 | """tests/test_interchange.py: stdlib-only referee for `ollm-interchange` (native/univ/interchange.om). |
| 4 | |
| 5 | Covers the Phase 3 universal weight interchange contract: |
| 6 | * import-hf (llama, mistral, qwen2, qwen3, gemma, helix; F32/BF16/F16/F64 safetensors) |
| 7 | * export-hf (f32 and bf16 HF directories: config.json + model.safetensors) |
| 8 | * export-gguf (GGUF v3, 32-byte aligned F32 tensors, llama q/k row permutation) |
| 9 | * upgrade (OLLMCK01/02/03 -> OLLMCK04, bit-exact p/m/v) |
| 10 | * fail-closed exit codes 2, 70, 80-88 and checkpoint refusals 10-15. |
| 11 | |
| 12 | Numerical parity is checked against an independent pure-Python f64 HF-semantics forward |
| 13 | (RMSNorm, rotate-half RoPE, GQA causal attention, SwiGLU / tanh-GeGLU, tied/untied heads) and |
| 14 | `ollm-univ eval` / `ollm-univ sample`; legacy upgrade parity against `ollm-macos eval`. |
| 15 | |
| 16 | Build: |
| 17 | TARGET=interchange OUT=/tmp/swarm-interchange sh scripts/build.sh |
| 18 | TARGET=univ OUT=/tmp/swarm-interchange sh scripts/build.sh |
| 19 | TARGET=macos OUT=/tmp/swarm-interchange sh scripts/build.sh |
| 20 | Run: |
| 21 | python3 tests/test_interchange.py -v |
| 22 | Env overrides: IX_OUT (default /tmp/swarm-interchange), IX_BIN, UNIV_BIN, LEGACY_BIN. |
| 23 | """ |
| 24 | |
| 25 | import json |
| 26 | import math |
| 27 | import os |
| 28 | import random |
| 29 | import shutil |
| 30 | import struct |
| 31 | import subprocess |
| 32 | import tempfile |
| 33 | import unittest |
| 34 | from collections import OrderedDict |
| 35 | |
| 36 | HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 37 | OUT = os.environ.get("IX_OUT", "/tmp/swarm-interchange") |
| 38 | |
| 39 | |
| 40 | def _pick(env, name): |
| 41 | if os.environ.get(env): |
| 42 | return os.environ[env] |
| 43 | for d in (OUT, "/tmp/omega-helix-verify-mac"): |
| 44 | p = os.path.join(d, name) |
| 45 | if os.path.isfile(p) and os.access(p, os.X_OK): |
| 46 | return p |
| 47 | return os.path.join(OUT, name) |
| 48 | |
| 49 | |
| 50 | IX_BIN = _pick("IX_BIN", "ollm-interchange") |
| 51 | UNIV_BIN = _pick("UNIV_BIN", "ollm-univ") |
| 52 | LEGACY_BIN = _pick("LEGACY_BIN", "ollm-macos") |
| 53 | |
| 54 | |
| 55 | def have(p): |
| 56 | return os.path.isfile(p) and os.access(p, os.X_OK) |
| 57 | |
| 58 | |
| 59 | HAVE_IX = have(IX_BIN) |
| 60 | HAVE_UNIV = have(UNIV_BIN) |
| 61 | HAVE_LEGACY = have(LEGACY_BIN) |
| 62 | |
| 63 | MAGIC_CK4 = 3760588441286102095 |
| 64 | MAGIC_CK1 = 3544415659172318287 |
| 65 | MAGIC_CK2 = 3616473253210246223 |
| 66 | MAGIC_CK3 = 3688530847248174159 |
| 67 | GGUF_MAGIC = 1179993927 |
| 68 | LN2 = 0.6931471805599453 |
| 69 | |
| 70 | |
| 71 | def run(bin_, *args, timeout=300): |
| 72 | r = subprocess.run([bin_] + [str(a) for a in args], capture_output=True, timeout=timeout) |
| 73 | return r.returncode, r.stdout.decode("latin-1"), r.stderr.decode("latin-1") |
| 74 | |
| 75 | |
| 76 | # ----------------------------------------------------------------------------- numerics |
| 77 | |
| 78 | def rb(path): |
| 79 | with open(path, "rb") as f: |
| 80 | return f.read() |
| 81 | |
| 82 | |
| 83 | def wb(path, data): |
| 84 | with open(path, "wb") as f: |
| 85 | f.write(data) |
| 86 | |
| 87 | |
| 88 | def jload(path): |
| 89 | with open(path) as f: |
| 90 | return json.load(f) |
| 91 | |
| 92 | |
| 93 | def dbytes(xs): |
| 94 | return struct.pack("<%dd" % len(xs), *xs) |
| 95 | |
| 96 | |
| 97 | def f32r(x): |
| 98 | return struct.unpack("<f", struct.pack("<f", x))[0] |
| 99 | |
| 100 | |
| 101 | def f64bits(x): |
| 102 | return struct.unpack("<Q", struct.pack("<d", x))[0] |
| 103 | |
| 104 | |
| 105 | def bf16_rne(x): |
| 106 | """f64 -> bf16 bits, single round-to-nearest-even directly from f64.""" |
| 107 | if x != x: |
| 108 | return 0x7FC0 |
| 109 | b = f64bits(x) |
| 110 | sign = b >> 63 |
| 111 | e = (b >> 52) & 0x7FF |
| 112 | m = b & ((1 << 52) - 1) |
| 113 | if e == 0x7FF: |
| 114 | return (sign << 15) | 0x7F80 |
| 115 | if e == 0: |
| 116 | return sign << 15 |
| 117 | E = e - 1023 |
| 118 | M = (1 << 52) | m |
| 119 | if E < -126: # bf16 subnormal, unit 2^-133; value = M * 2^(E-52) |
| 120 | sh = (52 - E) - 133 |
| 121 | if sh > 60: |
| 122 | return sign << 15 |
| 123 | q, rem = M >> sh, M & ((1 << sh) - 1) |
| 124 | half = 1 << (sh - 1) |
| 125 | if rem > half or (rem == half and (q & 1)): |
| 126 | q += 1 |
| 127 | return (sign << 15) | q |
| 128 | q, rem = M >> 45, M & ((1 << 45) - 1) |
| 129 | half = 1 << 44 |
| 130 | if rem > half or (rem == half and (q & 1)): |
| 131 | q += 1 |
| 132 | if q == (1 << 8): |
| 133 | q >>= 1 |
| 134 | E += 1 |
| 135 | if E > 127: |
| 136 | return (sign << 15) | 0x7F80 |
| 137 | return (sign << 15) | ((E + 127) << 7) | (q & 0x7F) |
| 138 | |
| 139 | |
| 140 | def bf16_val(bits): |
| 141 | return struct.unpack("<f", struct.pack("<I", (bits & 0xFFFF) << 16))[0] |
| 142 | |
| 143 | |
| 144 | DTSIZE = {"F32": 4, "F64": 8, "F16": 2, "BF16": 2} |
| 145 | |
| 146 | |
| 147 | def encode(vals, dt): |
| 148 | n = len(vals) |
| 149 | if dt == "F32": |
| 150 | return struct.pack("<%df" % n, *vals) |
| 151 | if dt == "F64": |
| 152 | return struct.pack("<%dd" % n, *vals) |
| 153 | if dt == "F16": |
| 154 | return struct.pack("<%de" % n, *vals) |
| 155 | if dt == "BF16": |
| 156 | return struct.pack("<%dH" % n, *[bf16_rne(v) for v in vals]) |
| 157 | raise ValueError(dt) |
| 158 | |
| 159 | |
| 160 | def decode(raw, dt): |
| 161 | n = len(raw) // DTSIZE[dt] |
| 162 | if dt == "F32": |
| 163 | return list(struct.unpack("<%df" % n, raw)) |
| 164 | if dt == "F64": |
| 165 | return list(struct.unpack("<%dd" % n, raw)) |
| 166 | if dt == "F16": |
| 167 | return list(struct.unpack("<%de" % n, raw)) |
| 168 | if dt == "BF16": |
| 169 | return [bf16_val(h) for h in struct.unpack("<%dH" % n, raw)] |
| 170 | raise ValueError(dt) |
| 171 | |
| 172 | |
| 173 | def quantize(vals, dt): |
| 174 | return decode(encode(vals, dt), dt) |
| 175 | |
| 176 | |
| 177 | def urmic(v): |
| 178 | """round half away from zero of the single f64 product v*1e6 (umath.om urmic).""" |
| 179 | x = v * 1000000.0 |
| 180 | q = int(x) |
| 181 | fr = x - q |
| 182 | if fr >= 0.5: |
| 183 | q += 1 |
| 184 | if fr <= -0.5: |
| 185 | q -= 1 |
| 186 | return q |
| 187 | |
| 188 | |
| 189 | def fnv1a(data): |
| 190 | h = 14695981039346656037 |
| 191 | for c in data: |
| 192 | h = ((h ^ c) * 1099511628211) & 0xFFFFFFFFFFFFFFFF |
| 193 | return h |
| 194 | |
| 195 | |
| 196 | def transpose(flat, R, C): |
| 197 | """[R][C] row-major -> [C][R] row-major.""" |
| 198 | out = [0.0] * (R * C) |
| 199 | for r in range(R): |
| 200 | base = r * C |
| 201 | for c in range(C): |
| 202 | out[c * R + r] = flat[base + c] |
| 203 | return out |
| 204 | |
| 205 | |
| 206 | # ----------------------------------------------------------------------------- safetensors |
| 207 | |
| 208 | def st_bytes(tensors, metadata=None, align=8, raw_header=None, extra_tail=b""): |
| 209 | """tensors: list of (name, dtype, shape, raw). Returns file bytes.""" |
| 210 | if raw_header is None: |
| 211 | hdr = OrderedDict() |
| 212 | if metadata is not None: |
| 213 | hdr["__metadata__"] = metadata |
| 214 | off = 0 |
| 215 | for name, dt, shape, raw in tensors: |
| 216 | hdr[name] = {"dtype": dt, "shape": list(shape), "data_offsets": [off, off + len(raw)]} |
| 217 | off += len(raw) |
| 218 | hj = json.dumps(hdr, separators=(",", ":")).encode() |
| 219 | else: |
| 220 | hj = raw_header |
| 221 | hj += b" " * ((-(8 + len(hj))) % align) |
| 222 | return struct.pack("<Q", len(hj)) + hj + b"".join(t[3] for t in tensors) + extra_tail |
| 223 | |
| 224 | |
| 225 | def st_parse(b): |
| 226 | n = struct.unpack_from("<Q", b, 0)[0] |
| 227 | hraw = b[8:8 + n] |
| 228 | seen = [] |
| 229 | |
| 230 | def hook(pairs): |
| 231 | keys = [k for k, _ in pairs] |
| 232 | if len(keys) != len(set(keys)): |
| 233 | raise ValueError("duplicate key") |
| 234 | return OrderedDict(pairs) |
| 235 | |
| 236 | hdr = json.loads(hraw.decode("utf-8"), object_pairs_hook=hook) |
| 237 | meta = hdr.pop("__metadata__", None) |
| 238 | ents = [] |
| 239 | for name, e in hdr.items(): |
| 240 | ents.append((name, e["dtype"], e["shape"], e["data_offsets"])) |
| 241 | return n, hraw, meta, ents, b[8 + n:] |
| 242 | |
| 243 | |
| 244 | # ----------------------------------------------------------------------------- HF model generation |
| 245 | |
| 246 | GEOM = dict(D=16, H=4, HKV=2, F=24, L=2, T=16) |
| 247 | |
| 248 | |
| 249 | class HFModel: |
| 250 | """A synthetic HF checkpoint (values are the f64 decoding of the stored dtype).""" |
| 251 | |
| 252 | def __init__(self, kind, V, D=16, H=4, HKV=2, F=24, L=2, T=16, tied=None, dtype="F32", |
| 253 | seed=1, theta=None, eps=None, dtype_of=None): |
| 254 | self.kind, self.V, self.D, self.H, self.HKV, self.F, self.L, self.T = kind, V, D, H, HKV, F, L, T |
| 255 | self.E = D // H |
| 256 | self.KVD = HKV * self.E |
| 257 | if tied is None: |
| 258 | tied = kind == "gemma" |
| 259 | self.tied = tied |
| 260 | self.theta = theta if theta is not None else {"qwen2": 1000000.0, "qwen3": 1000000.0}.get(kind, 10000.0) |
| 261 | self.eps = eps if eps is not None else {"llama": 1e-5, "mistral": 1e-5}.get(kind, 1e-6) |
| 262 | self.gemma = kind == "gemma" |
| 263 | self.qkn = kind == "qwen3" |
| 264 | self.t = OrderedDict() # name -> (shape, vals) |
| 265 | self.dt = {} |
| 266 | rng = random.Random(seed * 7919 + V) |
| 267 | |
| 268 | def add(name, shape, std, base=0.0): |
| 269 | n = 1 |
| 270 | for s in shape: |
| 271 | n *= s |
| 272 | vals = [] |
| 273 | for _ in range(n): |
| 274 | v = base + rng.gauss(0.0, std) |
| 275 | if base == 0.0 and abs(v) < 1e-3: |
| 276 | v = 1e-3 if v >= 0 else -1e-3 |
| 277 | vals.append(v) |
| 278 | d = dtype_of(name) if dtype_of else dtype |
| 279 | self.t[name] = (list(shape), quantize(vals, d)) |
| 280 | self.dt[name] = d |
| 281 | |
| 282 | nb = 0.0 if self.gemma else 1.0 |
| 283 | add("model.embed_tokens.weight", (V, D), 0.15) |
| 284 | for l in range(L): |
| 285 | p = "model.layers.%d." % l |
| 286 | add(p + "input_layernorm.weight", (D,), 0.1, nb) |
| 287 | add(p + "self_attn.q_proj.weight", (D, D), 0.5) |
| 288 | add(p + "self_attn.k_proj.weight", (self.KVD, D), 0.5) |
| 289 | add(p + "self_attn.v_proj.weight", (self.KVD, D), 0.5) |
| 290 | add(p + "self_attn.o_proj.weight", (D, D), 0.5) |
| 291 | if self.qkn: |
| 292 | add(p + "self_attn.q_norm.weight", (self.E,), 0.1, 1.0) |
| 293 | add(p + "self_attn.k_norm.weight", (self.E,), 0.1, 1.0) |
| 294 | add(p + "post_attention_layernorm.weight", (D,), 0.1, nb) |
| 295 | add(p + "mlp.gate_proj.weight", (F, D), 0.5) |
| 296 | add(p + "mlp.up_proj.weight", (F, D), 0.5) |
| 297 | add(p + "mlp.down_proj.weight", (D, F), 0.5) |
| 298 | add("model.norm.weight", (D,), 0.1, nb) |
| 299 | if not tied: |
| 300 | add("lm_head.weight", (V, D), 0.3) |
| 301 | |
| 302 | def config(self): |
| 303 | arch = {"llama": "LlamaForCausalLM", "mistral": "MistralForCausalLM", "qwen2": "Qwen2ForCausalLM", |
| 304 | "qwen3": "Qwen3ForCausalLM", "gemma": "GemmaForCausalLM"}[self.kind] |
| 305 | c = OrderedDict() |
| 306 | c["architectures"] = [arch] |
| 307 | c["model_type"] = self.kind |
| 308 | c["vocab_size"] = self.V |
| 309 | c["hidden_size"] = self.D |
| 310 | c["intermediate_size"] = self.F |
| 311 | c["num_hidden_layers"] = self.L |
| 312 | c["num_attention_heads"] = self.H |
| 313 | c["num_key_value_heads"] = self.HKV |
| 314 | c["head_dim"] = self.E |
| 315 | c["max_position_embeddings"] = self.T |
| 316 | c["rms_norm_eps"] = self.eps |
| 317 | c["rope_theta"] = self.theta |
| 318 | c["tie_word_embeddings"] = self.tied |
| 319 | c["hidden_act"] = "gelu_pytorch_tanh" if self.gemma else "silu" |
| 320 | if self.gemma: |
| 321 | c["hidden_activation"] = "gelu_pytorch_tanh" |
| 322 | c["attention_bias"] = False |
| 323 | c["rope_scaling"] = None |
| 324 | c["torch_dtype"] = "float32" |
| 325 | if self.kind == "mistral": |
| 326 | c["sliding_window"] = None |
| 327 | if self.kind == "qwen2": |
| 328 | c["use_sliding_window"] = False |
| 329 | c["sliding_window"] = 32768 |
| 330 | return c |
| 331 | |
| 332 | def st_tensors(self, names=None): |
| 333 | out = [] |
| 334 | for name, (shape, vals) in self.t.items(): |
| 335 | if names is not None and name not in names: |
| 336 | continue |
| 337 | out.append((name, self.dt[name], shape, encode(vals, self.dt[name]))) |
| 338 | return out |
| 339 | |
| 340 | def write(self, d, cfg=None, tensors=None, st=None): |
| 341 | os.makedirs(d, exist_ok=True) |
| 342 | cp, sp = os.path.join(d, "config.json"), os.path.join(d, "model.safetensors") |
| 343 | with open(cp, "w") as f: |
| 344 | if isinstance(cfg, (bytes, str)): |
| 345 | f.write(cfg if isinstance(cfg, str) else cfg.decode()) |
| 346 | else: |
| 347 | json.dump(cfg if cfg is not None else self.config(), f, indent=2) |
| 348 | with open(sp, "wb") as f: |
| 349 | f.write(st if st is not None else st_bytes(tensors if tensors is not None else self.st_tensors(), |
| 350 | metadata={"format": "pt"})) |
| 351 | return cp, sp |
| 352 | |
| 353 | # ---- flags & expected CK |
| 354 | def flags(self): |
| 355 | if self.kind == "gemma": |
| 356 | return 1 | 64 | 16 | 4 |
| 357 | f = 1 | 2 | 16 |
| 358 | if self.kind == "qwen3": |
| 359 | f |= 8 |
| 360 | if not self.tied: |
| 361 | f |= 4 |
| 362 | return f |
| 363 | |
| 364 | def expected_p(self): |
| 365 | D, F, V, E, KVD = self.D, self.F, self.V, self.E, self.KVD |
| 366 | g = self.gemma |
| 367 | t = lambda n: self.t[n][1] |
| 368 | sq = math.sqrt(D) |
| 369 | nrm = (lambda v: [1.0 + x for x in v]) if g else (lambda v: list(v)) |
| 370 | emb = t("model.embed_tokens.weight") |
| 371 | p = [x * sq for x in emb] if g else list(emb) |
| 372 | for l in range(self.L): |
| 373 | pre = "model.layers.%d." % l |
| 374 | p += nrm(t(pre + "input_layernorm.weight")) |
| 375 | p += transpose(t(pre + "self_attn.q_proj.weight"), D, D) |
| 376 | p += transpose(t(pre + "self_attn.k_proj.weight"), KVD, D) |
| 377 | p += transpose(t(pre + "self_attn.v_proj.weight"), KVD, D) |
| 378 | p += transpose(t(pre + "self_attn.o_proj.weight"), D, D) |
| 379 | if self.qkn: |
| 380 | p += list(t(pre + "self_attn.q_norm.weight")) |
| 381 | p += list(t(pre + "self_attn.k_norm.weight")) |
| 382 | p += nrm(t(pre + "post_attention_layernorm.weight")) |
| 383 | p += transpose(t(pre + "mlp.gate_proj.weight"), F, D) |
| 384 | p += transpose(t(pre + "mlp.up_proj.weight"), F, D) |
| 385 | p += transpose(t(pre + "mlp.down_proj.weight"), D, F) |
| 386 | p += nrm(t("model.norm.weight")) |
| 387 | if g: |
| 388 | p += list(emb) |
| 389 | elif not self.tied: |
| 390 | p += list(t("lm_head.weight")) |
| 391 | return p |
| 392 | |
| 393 | # ---- independent HF-semantics f64 forward |
| 394 | def logits(self, toks): |
| 395 | D, H, HKV, E, F, V = self.D, self.H, self.HKV, self.E, self.F, self.V |
| 396 | W = {n: v for n, (s, v) in self.t.items()} |
| 397 | g = self.gemma |
| 398 | eps = self.eps |
| 399 | |
| 400 | def rows(name, R, C): |
| 401 | v = W[name] |
| 402 | return [v[r * C:(r + 1) * C] for r in range(R)] |
| 403 | |
| 404 | def lin(M, x): |
| 405 | return [sum(a * b for a, b in zip(r, x)) for r in M] |
| 406 | |
| 407 | def rms(x, w, gem): |
| 408 | s = sum(v * v for v in x) / len(x) |
| 409 | inv = 1.0 / math.sqrt(s + eps) |
| 410 | if gem: |
| 411 | return [x[i] * inv * (1.0 + w[i]) for i in range(len(x))] |
| 412 | return [x[i] * inv * w[i] for i in range(len(x))] |
| 413 | |
| 414 | half = E // 2 |
| 415 | inv_freq = [1.0 / (self.theta ** ((2 * i) / E)) for i in range(half)] |
| 416 | |
| 417 | def rope(v, pos): |
| 418 | out = list(v) |
| 419 | for i in range(half): |
| 420 | c, s = math.cos(pos * inv_freq[i]), math.sin(pos * inv_freq[i]) |
| 421 | x1, x2 = v[i], v[i + half] |
| 422 | out[i] = x1 * c - x2 * s |
| 423 | out[i + half] = x2 * c + x1 * s |
| 424 | return out |
| 425 | |
| 426 | def act(x): |
| 427 | if g: |
| 428 | return 0.5 * x * (1.0 + math.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * x * x * x))) |
| 429 | return x / (1.0 + math.exp(-x)) |
| 430 | |
| 431 | T = len(toks) |
| 432 | emb = W["model.embed_tokens.weight"] |
| 433 | sq = math.sqrt(D) |
| 434 | h = [] |
| 435 | for tk in toks: |
| 436 | row = emb[tk * D:(tk + 1) * D] |
| 437 | h.append([x * sq for x in row] if g else list(row)) |
| 438 | rep = H // HKV |
| 439 | for l in range(self.L): |
| 440 | pre = "model.layers.%d." % l |
| 441 | Wq = rows(pre + "self_attn.q_proj.weight", D, D) |
| 442 | Wk = rows(pre + "self_attn.k_proj.weight", HKV * E, D) |
| 443 | Wv = rows(pre + "self_attn.v_proj.weight", HKV * E, D) |
| 444 | Wo = rows(pre + "self_attn.o_proj.weight", D, D) |
| 445 | Wg = rows(pre + "mlp.gate_proj.weight", F, D) |
| 446 | Wu = rows(pre + "mlp.up_proj.weight", F, D) |
| 447 | Wd = rows(pre + "mlp.down_proj.weight", D, F) |
| 448 | g1 = W[pre + "input_layernorm.weight"] |
| 449 | g2 = W[pre + "post_attention_layernorm.weight"] |
| 450 | Q, K, Vv = [], [], [] |
| 451 | for t in range(T): |
| 452 | a = rms(h[t], g1, g) |
| 453 | q, k, v = lin(Wq, a), lin(Wk, a), lin(Wv, a) |
| 454 | qh = [q[i * E:(i + 1) * E] for i in range(H)] |
| 455 | kh = [k[i * E:(i + 1) * E] for i in range(HKV)] |
| 456 | vh = [v[i * E:(i + 1) * E] for i in range(HKV)] |
| 457 | if self.qkn: |
| 458 | qn = W[pre + "self_attn.q_norm.weight"] |
| 459 | kn = W[pre + "self_attn.k_norm.weight"] |
| 460 | qh = [rms(x, qn, False) for x in qh] |
| 461 | kh = [rms(x, kn, False) for x in kh] |
| 462 | Q.append([rope(x, t) for x in qh]) |
| 463 | K.append([rope(x, t) for x in kh]) |
| 464 | Vv.append(vh) |
| 465 | nh = [] |
| 466 | for t in range(T): |
| 467 | o = [] |
| 468 | for hi in range(H): |
| 469 | kv = hi // rep |
| 470 | sc = [sum(a * b for a, b in zip(Q[t][hi], K[j][kv])) / math.sqrt(E) for j in range(t + 1)] |
| 471 | mx = max(sc) |
| 472 | ex = [math.exp(s - mx) for s in sc] |
| 473 | z = sum(ex) |
| 474 | acc = [0.0] * E |
| 475 | for j in range(t + 1): |
| 476 | w = ex[j] / z |
| 477 | for c in range(E): |
| 478 | acc[c] += w * Vv[j][kv][c] |
| 479 | o += acc |
| 480 | ao = lin(Wo, o) |
| 481 | hm = [h[t][i] + ao[i] for i in range(D)] |
| 482 | b = rms(hm, g2, g) |
| 483 | gt, up = lin(Wg, b), lin(Wu, b) |
| 484 | f = [act(gt[i]) * up[i] for i in range(F)] |
| 485 | dn = lin(Wd, f) |
| 486 | nh.append([hm[i] + dn[i] for i in range(D)]) |
| 487 | h = nh |
| 488 | gf = W["model.norm.weight"] |
| 489 | head = W["model.embed_tokens.weight"] if (self.tied or g) else W["lm_head.weight"] |
| 490 | Hd = [head[c * D:(c + 1) * D] for c in range(V)] |
| 491 | out = [] |
| 492 | for t in range(T): |
| 493 | z = rms(h[t], gf, g) |
| 494 | out.append([sum(a * b for a, b in zip(r, z)) for r in Hd]) |
| 495 | return out |
| 496 | |
| 497 | def seq_loss(self, x, y): |
| 498 | lg = self.logits(x) |
| 499 | tot = 0.0 |
| 500 | for t, row in enumerate(lg): |
| 501 | mx = max(row) |
| 502 | tot += math.log(sum(math.exp(v - mx) for v in row)) - (row[y[t]] - mx) |
| 503 | return tot / len(x) |
| 504 | |
| 505 | def eval_line(self, data, T, W, step=0): |
| 506 | s = 0.0 |
| 507 | for i in range(W): |
| 508 | o = i * T |
| 509 | s += self.seq_loss(data[o:o + T], data[o + 1:o + T + 1]) |
| 510 | ml = s / W |
| 511 | return ml, (step, W, urmic(ml), urmic(ml / LN2)) |
| 512 | |
| 513 | def greedy(self, n): |
| 514 | seq, out, safe = [0], [], True |
| 515 | for _ in range(n): |
| 516 | row = self.logits(seq)[-1] |
| 517 | best = 0 |
| 518 | for c in range(len(row)): |
| 519 | if row[c] > row[best]: |
| 520 | best = c |
| 521 | srt = sorted(row, reverse=True) |
| 522 | if srt[0] - srt[1] < 1e-9: |
| 523 | safe = False |
| 524 | out.append(best) |
| 525 | seq.append(best) |
| 526 | if not safe: |
| 527 | break |
| 528 | return out, safe |
| 529 | |
| 530 | |
| 531 | def tok_width(V): |
| 532 | return 1 if V <= 256 else (2 if V <= 65535 else 4) |
| 533 | |
| 534 | |
| 535 | def write_tokens(path, toks, V): |
| 536 | w = tok_width(V) |
| 537 | fmt = {1: "B", 2: "H", 4: "I"}[w] |
| 538 | with open(path, "wb") as f: |
| 539 | f.write(struct.pack("<%d%s" % (len(toks), fmt), *toks)) |
| 540 | |
| 541 | |
| 542 | # ----------------------------------------------------------------------------- OLLMCK04 |
| 543 | |
| 544 | CK4_FIELDS = ["V", "T", "D", "H", "HKV", "F", "L", "B", "seed", "step", "total", "lr_bits", "P", |
| 545 | "flags", "theta_milli", "eps_bits", "wd_bits", "warmup", "LP", "LC", "NP"] |
| 546 | |
| 547 | |
| 548 | def ck4_P(V, T, D, H, HKV, F, L, flags, **_): |
| 549 | E = D // H |
| 550 | KVD = HKV * E |
| 551 | rope, gated, untied, qkn = flags & 1, (flags & 66) != 0, flags & 4, flags & 8 |
| 552 | p = V * D + (0 if rope else T * D) |
| 553 | lay = D + D * D + 2 * D * KVD + D * D + (2 * E if qkn else 0) + D + D * F + (D * F if gated else 0) + F * D |
| 554 | p += L * lay + D |
| 555 | if untied: |
| 556 | p += V * D |
| 557 | return p |
| 558 | |
| 559 | |
| 560 | def ck4_segments(h): |
| 561 | """Ordered (name, rows, cols) list of the OLLMCK04 parameter layout (Helix [in][out]).""" |
| 562 | V, T, D, H, HKV, F, L, fl = h["V"], h["T"], h["D"], h["H"], h["HKV"], h["F"], h["L"], h["flags"] |
| 563 | E = D // H |
| 564 | KVD = HKV * E |
| 565 | segs = [("wte", V, D)] |
| 566 | if not fl & 1: |
| 567 | segs.append(("wpe", T, D)) |
| 568 | for l in range(L): |
| 569 | segs += [("g1.%d" % l, 1, D), ("wq.%d" % l, D, D), ("wk.%d" % l, D, KVD), ("wv.%d" % l, D, KVD), |
| 570 | ("wo.%d" % l, D, D)] |
| 571 | if fl & 8: |
| 572 | segs += [("qn.%d" % l, 1, E), ("kn.%d" % l, 1, E)] |
| 573 | segs.append(("g2.%d" % l, 1, D)) |
| 574 | segs.append(("w1.%d" % l, D, F)) |
| 575 | if fl & 66: |
| 576 | segs.append(("wup.%d" % l, D, F)) |
| 577 | segs.append(("w2.%d" % l, F, D)) |
| 578 | segs.append(("gf", 1, D)) |
| 579 | if fl & 4: |
| 580 | segs.append(("lmh", V, D)) |
| 581 | return segs |
| 582 | |
| 583 | |
| 584 | def ck4_read(path, check_fnv=True): |
| 585 | b = rb(path) |
| 586 | assert len(b) >= 208, "short CK04" |
| 587 | magic = struct.unpack_from("<Q", b, 0)[0] |
| 588 | assert magic == MAGIC_CK4, "bad CK04 magic %d" % magic |
| 589 | vals = struct.unpack_from("<21Q", b, 8) |
| 590 | h = dict(zip(CK4_FIELDS, vals)) |
| 591 | h["reserved"] = struct.unpack_from("<3Q", b, 176) |
| 592 | h["fnv"] = struct.unpack_from("<Q", b, 200)[0] |
| 593 | P = h["P"] |
| 594 | assert len(b) == 208 + 24 * P, "CK04 size %d != %d" % (len(b), 208 + 24 * P) |
| 595 | if check_fnv: |
| 596 | assert fnv1a(b[208:]) == h["fnv"], "CK04 FNV mismatch" |
| 597 | h["praw"] = b[208:208 + 8 * P] |
| 598 | h["mraw"] = b[208 + 8 * P:208 + 16 * P] |
| 599 | h["vraw"] = b[208 + 16 * P:] |
| 600 | h["p"] = list(struct.unpack_from("<%dd" % P, b, 208)) |
| 601 | h["raw"] = b |
| 602 | return h |
| 603 | |
| 604 | |
| 605 | def ck4_write(path, hdr, p): |
| 606 | P = len(p) |
| 607 | payload = dbytes(p) + b"\0" * (16 * P) |
| 608 | vals = [hdr[k] for k in CK4_FIELDS[:12]] + [P] + [hdr[k] for k in CK4_FIELDS[13:]] |
| 609 | head = struct.pack("<Q", MAGIC_CK4) + struct.pack("<21Q", *vals) + b"\0" * 24 + struct.pack("<Q", fnv1a(payload)) |
| 610 | with open(path, "wb") as f: |
| 611 | f.write(head + payload) |
| 612 | |
| 613 | |
| 614 | def ck4_split(h): |
| 615 | out, o = OrderedDict(), 0 |
| 616 | for name, r, c in ck4_segments(h): |
| 617 | out[name] = (r, c, h["p"][o:o + r * c]) |
| 618 | o += r * c |
| 619 | assert o == h["P"], "layout P %d != header P %d" % (o, h["P"]) |
| 620 | return out |
| 621 | |
| 622 | |
| 623 | def lp_lc_np(h): |
| 624 | return h["LP"], h["LC"], h["NP"] |
| 625 | |
| 626 | |
| 627 | def export_type(h, seg): |
| 628 | fl = h["flags"] |
| 629 | if h["NP"] <= 1 and fl & 1 and fl & 2 and fl & 8: |
| 630 | return "qwen3" |
| 631 | if h["NP"] <= 1 and fl & 1 and fl & 2: |
| 632 | return "llama" |
| 633 | if h["NP"] <= 1 and fl & 1 and fl & 64 and fl & 4: |
| 634 | sq = math.sqrt(h["D"]) |
| 635 | wte, lmh = seg["wte"][2], seg["lmh"][2] |
| 636 | if dbytes(wte) == dbytes([x * sq for x in lmh]): |
| 637 | return "gemma" |
| 638 | return "helix" |
| 639 | |
| 640 | |
| 641 | def ck_to_hf(h, gguf=False): |
| 642 | """Expected export: (model_type, [(hf_name, hf_shape, values)]) from a parsed CK04. |
| 643 | gguf=True keeps gemma norms as the stored 1+w (GGUF rule).""" |
| 644 | seg = ck4_split(h) |
| 645 | mt = export_type(h, seg) |
| 646 | V, T, D, H, HKV, F, L, fl = h["V"], h["T"], h["D"], h["H"], h["HKV"], h["F"], h["L"], h["flags"] |
| 647 | E = D // H |
| 648 | KVD = HKV * E |
| 649 | gem = mt == "gemma" |
| 650 | nrm = (lambda v: [x - 1.0 for x in v]) if (gem and not gguf) else (lambda v: list(v)) |
| 651 | out = [] |
| 652 | out.append(("model.embed_tokens.weight", [V, D], list(seg["lmh"][2]) if gem else list(seg["wte"][2]))) |
| 653 | if not fl & 1: |
| 654 | out.append(("model.embed_positions.weight", [T, D], list(seg["wpe"][2]))) |
| 655 | for l in range(L): |
| 656 | pre = "model.layers.%d." % l |
| 657 | out.append((pre + "input_layernorm.weight", [D], nrm(seg["g1.%d" % l][2]))) |
| 658 | out.append((pre + "self_attn.q_proj.weight", [D, D], transpose(seg["wq.%d" % l][2], D, D))) |
| 659 | out.append((pre + "self_attn.k_proj.weight", [KVD, D], transpose(seg["wk.%d" % l][2], D, KVD))) |
| 660 | out.append((pre + "self_attn.v_proj.weight", [KVD, D], transpose(seg["wv.%d" % l][2], D, KVD))) |
| 661 | out.append((pre + "self_attn.o_proj.weight", [D, D], transpose(seg["wo.%d" % l][2], D, D))) |
| 662 | if fl & 8: |
| 663 | out.append((pre + "self_attn.q_norm.weight", [E], list(seg["qn.%d" % l][2]))) |
| 664 | out.append((pre + "self_attn.k_norm.weight", [E], list(seg["kn.%d" % l][2]))) |
| 665 | out.append((pre + "post_attention_layernorm.weight", [D], nrm(seg["g2.%d" % l][2]))) |
| 666 | if fl & 66: |
| 667 | out.append((pre + "mlp.gate_proj.weight", [F, D], transpose(seg["w1.%d" % l][2], D, F))) |
| 668 | out.append((pre + "mlp.up_proj.weight", [F, D], transpose(seg["wup.%d" % l][2], D, F))) |
| 669 | else: |
| 670 | out.append((pre + "mlp.up_proj.weight", [F, D], transpose(seg["w1.%d" % l][2], D, F))) |
| 671 | out.append((pre + "mlp.down_proj.weight", [D, F], transpose(seg["w2.%d" % l][2], F, D))) |
| 672 | out.append(("model.norm.weight", [D], nrm(seg["gf"][2]))) |
| 673 | if fl & 4 and not gem: |
| 674 | out.append(("lm_head.weight", [V, D], list(seg["lmh"][2]))) |
| 675 | return mt, out |
| 676 | |
| 677 | |
| 678 | GGUF_NAME = [ |
| 679 | ("model.embed_tokens.weight", "token_embd.weight"), |
| 680 | ("model.embed_positions.weight", "position_embd.weight"), |
| 681 | ("input_layernorm.weight", "attn_norm.weight"), |
| 682 | ("self_attn.q_proj.weight", "attn_q.weight"), |
| 683 | ("self_attn.k_proj.weight", "attn_k.weight"), |
| 684 | ("self_attn.v_proj.weight", "attn_v.weight"), |
| 685 | ("self_attn.o_proj.weight", "attn_output.weight"), |
| 686 | ("self_attn.q_norm.weight", "attn_q_norm.weight"), |
| 687 | ("self_attn.k_norm.weight", "attn_k_norm.weight"), |
| 688 | ("post_attention_layernorm.weight", "ffn_norm.weight"), |
| 689 | ("mlp.gate_proj.weight", "ffn_gate.weight"), |
| 690 | ("mlp.up_proj.weight", "ffn_up.weight"), |
| 691 | ("mlp.down_proj.weight", "ffn_down.weight"), |
| 692 | ("model.norm.weight", "output_norm.weight"), |
| 693 | ("lm_head.weight", "output.weight"), |
| 694 | ] |
| 695 | |
| 696 | |
| 697 | def gguf_name(hf): |
| 698 | if hf.startswith("model.layers."): |
| 699 | rest = hf[len("model.layers."):] |
| 700 | n, tail = rest.split(".", 1) |
| 701 | for a, b in GGUF_NAME: |
| 702 | if tail == a: |
| 703 | return "blk.%s.%s" % (n, b) |
| 704 | raise KeyError(hf) |
| 705 | for a, b in GGUF_NAME: |
| 706 | if hf == a: |
| 707 | return b |
| 708 | raise KeyError(hf) |
| 709 | |
| 710 | |
| 711 | def llama_permute(vals, rows_total, cols, n_head): |
| 712 | E = rows_total // n_head |
| 713 | out = [0.0] * len(vals) |
| 714 | for hh in range(n_head): |
| 715 | for a in range(2): |
| 716 | for b in range(E // 2): |
| 717 | dst = hh * E + 2 * b + a |
| 718 | src = hh * E + a * (E // 2) + b |
| 719 | out[dst * cols:(dst + 1) * cols] = vals[src * cols:(src + 1) * cols] |
| 720 | return out |
| 721 | |
| 722 | |
| 723 | # ----------------------------------------------------------------------------- GGUF parser |
| 724 | |
| 725 | def gguf_parse(b): |
| 726 | pos = [0] |
| 727 | |
| 728 | def rd(fmt): |
| 729 | v = struct.unpack_from("<" + fmt, b, pos[0]) |
| 730 | pos[0] += struct.calcsize("<" + fmt) |
| 731 | return v[0] if len(v) == 1 else v |
| 732 | |
| 733 | def rstr(): |
| 734 | n = rd("Q") |
| 735 | s = b[pos[0]:pos[0] + n] |
| 736 | pos[0] += n |
| 737 | return s.decode("utf-8") |
| 738 | |
| 739 | scal = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"} |
| 740 | |
| 741 | def rval(t): |
| 742 | if t in scal: |
| 743 | return rd(scal[t]) |
| 744 | if t == 8: |
| 745 | return rstr() |
| 746 | if t == 9: |
| 747 | at, n = rd("I"), rd("Q") |
| 748 | return [rval(at) for _ in range(n)] |
| 749 | raise ValueError("gguf kv type %d" % t) |
| 750 | |
| 751 | magic, ver, nt, nkv = rd("I"), rd("I"), rd("Q"), rd("Q") |
| 752 | kvs = OrderedDict() |
| 753 | for _ in range(nkv): |
| 754 | k = rstr() |
| 755 | t = rd("I") |
| 756 | kvs[k] = (t, rval(t)) |
| 757 | tens = [] |
| 758 | for _ in range(nt): |
| 759 | name = rstr() |
| 760 | nd = rd("I") |
| 761 | dims = [rd("Q") for _ in range(nd)] |
| 762 | typ = rd("I") |
| 763 | off = rd("Q") |
| 764 | tens.append((name, dims, typ, off)) |
| 765 | return dict(magic=magic, version=ver, nt=nt, nkv=nkv, kvs=kvs, tensors=tens, info_end=pos[0]) |
| 766 | |
| 767 | |
| 768 | # ----------------------------------------------------------------------------- legacy CK01/02/03 |
| 769 | |
| 770 | def legacy_read(path): |
| 771 | b = rb(path) |
| 772 | mg = struct.unpack_from("<Q", b, 0)[0] |
| 773 | hl = {MAGIC_CK1: 112, MAGIC_CK2: 120, MAGIC_CK3: 144}[mg] |
| 774 | ver = {MAGIC_CK1: 1, MAGIC_CK2: 2, MAGIC_CK3: 3}[mg] |
| 775 | V, T, D, H, F, L, B = struct.unpack_from("<7Q", b, 8) |
| 776 | seed, step, total, lr, P = struct.unpack_from("<5Q", b, 64) |
| 777 | G = struct.unpack_from("<Q", b, 104)[0] if hl >= 120 else 1 |
| 778 | LP = LC = NP = 0 |
| 779 | if hl == 144: |
| 780 | LP, LC, NP = struct.unpack_from("<3Q", b, 112) |
| 781 | return dict(ver=ver, hl=hl, V=V, T=T, D=D, H=H, F=F, L=L, B=B, seed=seed, step=step, total=total, |
| 782 | lr_bits=lr, P=P, G=G, LP=LP, LC=LC, NP=NP, payload=b[hl:], raw=b) |
| 783 | |
| 784 | |
| 785 | # ============================================================================= tests |
| 786 | |
| 787 | class Base(unittest.TestCase): |
| 788 | maxDiff = 4000 |
| 789 | |
| 790 | def setUp(self): |
| 791 | self.tmp = tempfile.mkdtemp(prefix="ixtest-") |
| 792 | |
| 793 | def tearDown(self): |
| 794 | if os.environ.get("IX_KEEP") != "1": |
| 795 | shutil.rmtree(self.tmp, ignore_errors=True) |
| 796 | |
| 797 | def path(self, *p): |
| 798 | return os.path.join(self.tmp, *p) |
| 799 | |
| 800 | def ix(self, *args, rc=0, mkdir=True): |
| 801 | # contract (#12): export-hf requires OUT_DIR to exist; a missing OUT_DIR is exit 70 |
| 802 | if mkdir and len(args) >= 3 and args[0] == "export-hf": |
| 803 | os.makedirs(args[2], exist_ok=True) |
| 804 | r, o, e = run(IX_BIN, *args) |
| 805 | if rc is not None: |
| 806 | self.assertEqual(r, rc, "ollm-interchange %s -> rc %d (want %d)\nstdout=%r\nstderr=%r" % |
| 807 | (" ".join(map(str, args)), r, rc, o, e)) |
| 808 | return o |
| 809 | |
| 810 | def univ(self, *args, rc=0): |
| 811 | r, o, e = run(UNIV_BIN, *args) |
| 812 | self.assertEqual(r, rc, "ollm-univ %s -> rc %d\nstdout=%r stderr=%r" % (" ".join(map(str, args)), r, o, e)) |
| 813 | return o |
| 814 | |
| 815 | def assertBitsEqual(self, got, want, what): |
| 816 | if dbytes(got) != dbytes(want): |
| 817 | self.assertEqual(len(got), len(want), "%s: length %d != %d" % (what, len(got), len(want))) |
| 818 | for i, (a, b) in enumerate(zip(got, want)): |
| 819 | if f64bits(a) != f64bits(b): |
| 820 | self.fail("%s: first bit mismatch at %d: got %r want %r" % (what, i, a, b)) |
| 821 | |
| 822 | def eval_check(self, model, ck, nwin=3, seed=5): |
| 823 | rng = random.Random(seed + model.V) |
| 824 | T = model.T |
| 825 | data = [rng.randrange(model.V) for _ in range(nwin * T + 1 + 7)] |
| 826 | dp = self.path("data-%d.bin" % seed) |
| 827 | write_tokens(dp, data, model.V) |
| 828 | out = self.univ("eval", ck, dp, nwin).split() |
| 829 | self.assertEqual(out[0], "E") |
| 830 | ml, (step, W, lm, bm) = model.eval_line(data, T, nwin) |
| 831 | self.assertEqual(int(out[1]), step) |
| 832 | self.assertEqual(int(out[2]), W) |
| 833 | self.assertLessEqual(abs(int(out[3]) - lm), 1, "loss_micro engine %s vs ref %d (%.12f)" % (out[3], lm, ml)) |
| 834 | self.assertLessEqual(abs(int(out[4]) - bm), 1, "bpb_micro engine %s vs ref %d" % (out[4], bm)) |
| 835 | return int(out[3]), lm |
| 836 | |
| 837 | def sample_check(self, model, ck, n=None): |
| 838 | n = n or model.T |
| 839 | got = [int(x) for x in self.univ("sample", ck, 1, n, 0).split()] |
| 840 | want, safe = model.greedy(n) |
| 841 | self.assertEqual(got[:len(want)], want, "greedy sample engine %s vs ref %s" % (got, want)) |
| 842 | if safe: |
| 843 | self.assertEqual(len(got), n) |
| 844 | return got |
| 845 | |
| 846 | def hdr_expect(self, model, h, T=None, B=1, total=1000, lrmicro=100): |
| 847 | T = T or model.T |
| 848 | exp = dict(V=model.V, T=T, D=model.D, H=model.H, HKV=model.HKV, F=model.F, L=model.L, B=B, |
| 849 | seed=0, step=0, total=total, lr_bits=f64bits(lrmicro / 1000000.0), flags=model.flags(), |
| 850 | theta_milli=int(round(model.theta * 1000)), eps_bits=f64bits(model.eps)) |
| 851 | for k, v in exp.items(): |
| 852 | self.assertEqual(h[k], v, "CK04 header %s: got %r want %r" % (k, h[k], v)) |
| 853 | self.assertEqual(h["P"], ck4_P(**{k: h[k] for k in ("V", "T", "D", "H", "HKV", "F", "L", "flags")})) |
| 854 | self.assertEqual((h["LP"], h["LC"]), (0, 0)) |
| 855 | self.assertIn(h["NP"], (0, 1)) |
| 856 | self.assertEqual(h["mraw"], b"\0" * (8 * h["P"]), "Adam m not zero") |
| 857 | self.assertEqual(h["vraw"], b"\0" * (8 * h["P"]), "Adam v not zero") |
| 858 | |
| 859 | |
| 860 | # ----------------------------------------------------------------------------- oracle self-check |
| 861 | |
| 862 | @unittest.skipUnless(HAVE_UNIV, "ollm-univ not built (%s)" % UNIV_BIN) |
| 863 | class T00OracleSelfCheck(Base): |
| 864 | """Validates the Python HF-semantics reference against ollm-univ using a Python-written CK04 |
| 865 | (independent of ollm-interchange).""" |
| 866 | |
| 867 | def _one(self, kind, V, tied=None): |
| 868 | m = HFModel(kind, V, tied=tied, seed=3) |
| 869 | hdr = dict(V=m.V, T=m.T, D=m.D, H=m.H, HKV=m.HKV, F=m.F, L=m.L, B=1, seed=0, step=0, total=1000, |
| 870 | lr_bits=f64bits(1e-4), flags=m.flags(), theta_milli=int(round(m.theta * 1000)), |
| 871 | eps_bits=f64bits(m.eps), wd_bits=0, warmup=100, LP=0, LC=0, NP=0) |
| 872 | ck = self.path("py.ck") |
| 873 | ck4_write(ck, hdr, m.expected_p()) |
| 874 | info = self.univ("info", ck).split() |
| 875 | self.assertEqual(int(info[9]), len(m.expected_p())) |
| 876 | self.eval_check(m, ck) |
| 877 | self.sample_check(m, ck) |
| 878 | |
| 879 | def test_llama_tied(self): |
| 880 | self._one("llama", 96, tied=True) |
| 881 | |
| 882 | def test_qwen3_untied_u16(self): |
| 883 | self._one("qwen3", 300, tied=False) |
| 884 | |
| 885 | def test_gemma(self): |
| 886 | self._one("gemma", 80) |
| 887 | |
| 888 | |
| 889 | # ----------------------------------------------------------------------------- import-hf |
| 890 | |
| 891 | @unittest.skipUnless(HAVE_IX, "ollm-interchange not built (%s)" % IX_BIN) |
| 892 | class T10Import(Base): |
| 893 | |
| 894 | def do_import(self, m, extra=(), sub="hf", **kw): |
| 895 | cp, sp = m.write(self.path(sub), **kw) |
| 896 | ck = self.path(sub + ".ck") |
| 897 | out = self.ix("import-hf", cp, sp, ck, *extra) |
| 898 | return ck, out |
| 899 | |
| 900 | def check_stdout(self, out, m, h): |
| 901 | want = "I %d %d %d %d %d %d %d %d %d\n" % (m.V, h["T"], m.D, m.H, m.HKV, m.F, m.L, h["P"], m.flags()) |
| 902 | self.assertEqual(out, want) |
| 903 | |
| 904 | def test_dtypes(self): |
| 905 | for dt in ("F32", "BF16", "F16", "F64"): |
| 906 | with self.subTest(dtype=dt): |
| 907 | m = HFModel("llama", 96, dtype=dt, seed=11) |
| 908 | ck, out = self.do_import(m, sub="d" + dt) |
| 909 | h = ck4_read(ck) |
| 910 | self.hdr_expect(m, h) |
| 911 | self.check_stdout(out, m, h) |
| 912 | self.assertBitsEqual(h["p"], m.expected_p(), "llama %s params" % dt) |
| 913 | |
| 914 | def test_mixed_dtypes(self): |
| 915 | cyc = ["F32", "BF16", "F16", "F64"] |
| 916 | m = HFModel("qwen3", 72, tied=False, seed=12, |
| 917 | dtype_of=lambda n: cyc[sum(map(ord, n)) % 4]) |
| 918 | self.assertEqual(len(set(m.dt.values())), 4) |
| 919 | ck, out = self.do_import(m) |
| 920 | h = ck4_read(ck) |
| 921 | self.hdr_expect(m, h) |
| 922 | self.assertBitsEqual(h["p"], m.expected_p(), "mixed-dtype params") |
| 923 | |
| 924 | def _parity(self, kind, V, tied=None, dtype="F32", sample=True): |
| 925 | m = HFModel(kind, V, tied=tied, dtype=dtype, seed=21) |
| 926 | ck, out = self.do_import(m) |
| 927 | h = ck4_read(ck) |
| 928 | self.hdr_expect(m, h) |
| 929 | self.check_stdout(out, m, h) |
| 930 | self.assertBitsEqual(h["p"], m.expected_p(), "%s params" % kind) |
| 931 | self.eval_check(m, ck) |
| 932 | if sample: |
| 933 | self.sample_check(m, ck) |
| 934 | return m, ck |
| 935 | |
| 936 | @unittest.skipUnless(HAVE_UNIV, "ollm-univ missing") |
| 937 | def test_llama_parity(self): |
| 938 | self._parity("llama", 96, tied=True) |
| 939 | |
| 940 | @unittest.skipUnless(HAVE_UNIV, "ollm-univ missing") |
| 941 | def test_llama_untied_bf16_parity(self): |
| 942 | self._parity("llama", 64, tied=False, dtype="BF16") |
| 943 | |
| 944 | @unittest.skipUnless(HAVE_UNIV, "ollm-univ missing") |
| 945 | def test_qwen3_parity(self): |
| 946 | self._parity("qwen3", 300, tied=False) |
| 947 | |
| 948 | @unittest.skipUnless(HAVE_UNIV, "ollm-univ missing") |
| 949 | def test_qwen3_tied_parity(self): |
| 950 | self._parity("qwen3", 128, tied=True, sample=False) |
| 951 | |
| 952 | @unittest.skipUnless(HAVE_UNIV, "ollm-univ missing") |
| 953 | def test_gemma_parity(self): |
| 954 | self._parity("gemma", 80) |
| 955 | |
| 956 | @unittest.skipUnless(HAVE_UNIV, "ollm-univ missing") |
| 957 | def test_qwen2_parity(self): |
| 958 | self._parity("qwen2", 90, tied=False, sample=False) |
| 959 | |
| 960 | @unittest.skipUnless(HAVE_UNIV, "ollm-univ missing") |
| 961 | def test_mistral_parity(self): |
| 962 | self._parity("mistral", 70, tied=False, sample=False) |
| 963 | |
| 964 | def test_explicit_args(self): |
| 965 | m = HFModel("llama", 64, tied=True, seed=4) |
| 966 | ck, out = self.do_import(m, extra=(8, 2, 500, 3000)) |
| 967 | h = ck4_read(ck) |
| 968 | self.hdr_expect(m, h, T=8, B=2, total=500, lrmicro=3000) |
| 969 | self.check_stdout(out, m, h) |
| 970 | self.assertBitsEqual(h["p"], m.expected_p(), "explicit-args params") |
| 971 | |
| 972 | def test_default_T(self): |
| 973 | m = HFModel("llama", 64, tied=True, seed=4) |
| 974 | c = m.config() |
| 975 | c["max_position_embeddings"] = 4096 |
| 976 | ck, _ = self.do_import(m, sub="big", cfg=c) |
| 977 | self.assertEqual(ck4_read(ck)["T"], 256) |
| 978 | c2 = m.config() |
| 979 | del c2["max_position_embeddings"] |
| 980 | ck2, _ = self.do_import(m, sub="none", cfg=c2) |
| 981 | self.assertEqual(ck4_read(ck2)["T"], 256) |
| 982 | |
| 983 | def test_optional_fields_defaults(self): |
| 984 | m = HFModel("llama", 64, tied=False, seed=5, eps=1e-6, theta=10000.0, HKV=4) |
| 985 | c = m.config() |
| 986 | for k in ("num_key_value_heads", "rms_norm_eps", "rope_theta", "tie_word_embeddings", "head_dim", |
| 987 | "rope_scaling", "attention_bias", "torch_dtype", "architectures"): |
| 988 | del c[k] |
| 989 | ck, _ = self.do_import(m, cfg=c) |
| 990 | h = ck4_read(ck) |
| 991 | self.hdr_expect(m, h) |
| 992 | self.assertBitsEqual(h["p"], m.expected_p(), "defaults params") |
| 993 | |
| 994 | def test_ignored_and_zero_bias_tensors(self): |
| 995 | m = HFModel("qwen2", 64, tied=True, seed=6) |
| 996 | ref_ck, _ = self.do_import(m, sub="plain") |
| 997 | extra = list(m.st_tensors()) |
| 998 | D, KVD = m.D, m.KVD |
| 999 | for l in range(m.L): |
| 1000 | pre = "model.layers.%d." % l |
| 1001 | extra.append((pre + "self_attn.q_proj.bias", "F32", [D], encode([0.0] * D, "F32"))) |
| 1002 | extra.append((pre + "self_attn.k_proj.bias", "BF16", [KVD], encode([0.0] * KVD, "BF16"))) |
| 1003 | extra.append((pre + "self_attn.v_proj.bias", "F32", [KVD], encode([-0.0] * KVD, "F32"))) |
| 1004 | extra.append((pre + "self_attn.rotary_emb.inv_freq", "F32", [m.E // 2], encode([1.0, 0.01], "F32"))) |
| 1005 | extra.append(("lm_head.weight", "F32", [m.V, m.D], encode([0.5] * (m.V * m.D), "F32"))) # tied: ignored |
| 1006 | ck, _ = self.do_import(m, sub="extra", tensors=extra) |
| 1007 | self.assertEqual(rb(ck), rb(ref_ck)) |
| 1008 | |
| 1009 | def test_reordered_tensors_and_no_metadata(self): |
| 1010 | m = HFModel("llama", 64, tied=False, seed=7) |
| 1011 | ref_ck, _ = self.do_import(m, sub="plain") |
| 1012 | ts = list(reversed(m.st_tensors())) |
| 1013 | st = st_bytes(ts, metadata=None) |
| 1014 | ck, _ = self.do_import(m, sub="rev", st=st) |
| 1015 | self.assertEqual(rb(ck), rb(ref_ck)) |
| 1016 | |
| 1017 | |
| 1018 | # ----------------------------------------------------------------------------- export-hf / round trip |
| 1019 | |
| 1020 | @unittest.skipUnless(HAVE_IX, "ollm-interchange not built (%s)" % IX_BIN) |
| 1021 | class T20ExportHF(Base): |
| 1022 | |
| 1023 | CFG_KEYS = ["architectures", "model_type", "vocab_size", "hidden_size", "intermediate_size", |
| 1024 | "num_hidden_layers", "num_attention_heads", "num_key_value_heads", "head_dim", |
| 1025 | "max_position_embeddings", "rms_norm_eps", "rope_theta", "tie_word_embeddings", "hidden_act", |
| 1026 | "attention_bias", "rope_scaling", "torch_dtype", "helix_arch_flags", "helix_loop_lp", |
| 1027 | "helix_loop_lc", "helix_loop_np"] |
| 1028 | |
| 1029 | def check_export(self, ck, outdir, dt="f32", args=None): |
| 1030 | h = ck4_read(ck) |
| 1031 | mt, want = ck_to_hf(h) |
| 1032 | o = self.ix("export-hf", ck, outdir, *([dt] if args is None else args)) |
| 1033 | st = rb(os.path.join(outdir, "model.safetensors")) |
| 1034 | cfg = jload((os.path.join(outdir, "config.json"))) |
| 1035 | self.assertEqual(o, "XH %d %d\n" % (len(want), len(st))) |
| 1036 | # --- safetensors structure |
| 1037 | n, hraw, meta, ents, data = st_parse(st) |
| 1038 | self.assertTrue(2 <= n <= 983040) |
| 1039 | self.assertEqual((8 + n) % 8, 0, "header not padded to 8") |
| 1040 | js = hraw.rstrip(b" ") |
| 1041 | self.assertTrue(js.startswith(b'{"__metadata__"'), "first key must be __metadata__: %r" % hraw[:40]) |
| 1042 | self.assertTrue(all(c == 0x20 for c in hraw[len(js):]), "header padding must be spaces") |
| 1043 | self.assertEqual(meta, {"format": "pt"}) |
| 1044 | self.assertEqual([e[0] for e in ents], [w[0] for w in want], "tensor order") |
| 1045 | sdt = "F32" if dt == "f32" else "BF16" |
| 1046 | off = 0 |
| 1047 | for (name, edt, shape, (b0, b1)), (wn, wshape, wvals) in zip(ents, want): |
| 1048 | self.assertEqual(edt, sdt, name) |
| 1049 | self.assertEqual(shape, wshape, name) |
| 1050 | self.assertEqual(b0, off, "%s not contiguous" % name) |
| 1051 | self.assertEqual(b1 - b0, len(wvals) * DTSIZE[sdt], name) |
| 1052 | raw = data[b0:b1] |
| 1053 | if sdt == "F32": |
| 1054 | exp = struct.pack("<%df" % len(wvals), *wvals) |
| 1055 | else: |
| 1056 | exp = struct.pack("<%dH" % len(wvals), *[bf16_rne(v) for v in wvals]) |
| 1057 | if raw != exp: |
| 1058 | got = decode(raw, sdt) |
| 1059 | ref = decode(exp, sdt) |
| 1060 | bad = [i for i in range(len(got)) if dbytes([got[i]]) != dbytes([ref[i]])] |
| 1061 | self.fail("%s %s data mismatch at %d of %d (first idx %d: got %r want %r from f64 %r)" % |
| 1062 | (name, sdt, len(bad), len(got), bad[0], got[bad[0]], ref[bad[0]], wvals[bad[0]])) |
| 1063 | off = b1 |
| 1064 | self.assertEqual(len(data), off, "trailing data after last tensor") |
| 1065 | # --- config.json |
| 1066 | for k in self.CFG_KEYS: |
| 1067 | self.assertIn(k, cfg, "config.json missing %s" % k) |
| 1068 | D, H = h["D"], h["H"] |
| 1069 | self.assertEqual(cfg["model_type"], mt) |
| 1070 | self.assertIsInstance(cfg["architectures"], list) |
| 1071 | exp = dict(vocab_size=h["V"], hidden_size=D, intermediate_size=h["F"], num_hidden_layers=h["L"], |
| 1072 | num_attention_heads=H, num_key_value_heads=h["HKV"], head_dim=D // H, |
| 1073 | max_position_embeddings=h["T"], attention_bias=False, rope_scaling=None, |
| 1074 | torch_dtype="float32" if dt == "f32" else "bfloat16", helix_arch_flags=h["flags"], |
| 1075 | helix_loop_lp=h["LP"], helix_loop_lc=h["LC"], helix_loop_np=h["NP"]) |
| 1076 | for k, v in exp.items(): |
| 1077 | self.assertEqual(cfg[k], v, "config %s" % k) |
| 1078 | self.assertEqual(f64bits(float(cfg["rms_norm_eps"])), h["eps_bits"], "rms_norm_eps not bit-exact") |
| 1079 | self.assertEqual(float(cfg["rope_theta"]), h["theta_milli"] / 1000.0) |
| 1080 | tie = {"gemma": True}.get(mt, not (h["flags"] & 4)) |
| 1081 | self.assertEqual(cfg["tie_word_embeddings"], tie) |
| 1082 | if mt in ("llama", "qwen3"): |
| 1083 | self.assertEqual(cfg["hidden_act"], "silu") |
| 1084 | self.assertIsInstance(cfg["hidden_act"], str) |
| 1085 | return h, mt, want, st, cfg |
| 1086 | |
| 1087 | def _roundtrip_hf(self, kind, V, tied=None, sub="rt"): |
| 1088 | m = HFModel(kind, V, tied=tied, seed=31) |
| 1089 | cp, sp = m.write(self.path(sub)) |
| 1090 | ck1 = self.path(sub + "1.ck") |
| 1091 | self.ix("import-hf", cp, sp, ck1) |
| 1092 | out = self.path(sub + "-out") |
| 1093 | h, mt, want, st, cfg = self.check_export(ck1, out) |
| 1094 | self.assertEqual(mt, kind if kind != "mistral" and kind != "qwen2" else "llama") |
| 1095 | # byte-identical tensors vs the F32 source |
| 1096 | src = {name: raw for name, _, _, raw in m.st_tensors()} |
| 1097 | n, hraw, meta, ents, data = st_parse(st) |
| 1098 | self.assertEqual(sorted(e[0] for e in ents), sorted(src), "exported tensor set != source set") |
| 1099 | for name, _, _, (b0, b1) in ents: |
| 1100 | self.assertEqual(data[b0:b1], src[name], "%s not byte-identical to F32 source" % name) |
| 1101 | # re-import -> byte-identical CK |
| 1102 | ck2 = self.path(sub + "2.ck") |
| 1103 | self.ix("import-hf", os.path.join(out, "config.json"), os.path.join(out, "model.safetensors"), ck2) |
| 1104 | self.assertEqual(rb(ck2), rb(ck1), "re-imported CK not byte-identical") |
| 1105 | # bf16 export |
| 1106 | self.check_export(ck1, self.path(sub + "-bf16"), "bf16") |
| 1107 | return m, ck1 |
| 1108 | |
| 1109 | def test_llama_roundtrip(self): |
| 1110 | self._roundtrip_hf("llama", 96, tied=True) |
| 1111 | |
| 1112 | def test_qwen3_roundtrip(self): |
| 1113 | self._roundtrip_hf("qwen3", 300, tied=False) |
| 1114 | |
| 1115 | def test_gemma_roundtrip(self): |
| 1116 | self._roundtrip_hf("gemma", 80) |
| 1117 | |
| 1118 | def test_default_dtype_is_f32(self): |
| 1119 | m = HFModel("llama", 64, tied=False, seed=32) |
| 1120 | cp, sp = m.write(self.path("a")) |
| 1121 | ck = self.path("a.ck") |
| 1122 | self.ix("import-hf", cp, sp, ck) |
| 1123 | self.check_export(ck, self.path("o1"), args=[]) |
| 1124 | self.check_export(ck, self.path("o2"), "f32") |
| 1125 | for f in ("config.json", "model.safetensors"): |
| 1126 | self.assertEqual(rb(self.path("o1", f)), rb(self.path("o2", f))) |
| 1127 | |
| 1128 | # ---- helix / univ-init checkpoints (f64 weights -> f32 export -> f32-rounded reimport) |
| 1129 | def _helix(self, arch, V, D, H, HKV, F, L, T, extra=(), want_mt="helix"): |
| 1130 | if not HAVE_UNIV: |
| 1131 | self.skipTest("ollm-univ missing") |
| 1132 | ck = self.path("u.ck") |
| 1133 | self.univ("init", ck, arch, V, T, D, H, HKV, F, L, 1, 0, 1000, 100, *extra) |
| 1134 | h0 = ck4_read(ck) |
| 1135 | out = self.path("hx") |
| 1136 | h, mt, want, st, cfg = self.check_export(ck, out) |
| 1137 | self.assertEqual(mt, want_mt, "export model_type for arch %s flags %d" % (arch, h0["flags"])) |
| 1138 | if mt == "helix": |
| 1139 | self.assertIn("helix", json.dumps(cfg["architectures"]).lower() + cfg["model_type"]) |
| 1140 | ck2 = self.path("u2.ck") |
| 1141 | o = self.ix("import-hf", os.path.join(out, "config.json"), os.path.join(out, "model.safetensors"), ck2) |
| 1142 | h2 = ck4_read(ck2) |
| 1143 | for k in ("V", "T", "D", "H", "HKV", "F", "L", "P", "flags", "theta_milli", "eps_bits", "LP", "LC", "NP"): |
| 1144 | self.assertEqual(h2[k], h0[k], "reimport header %s" % k) |
| 1145 | self.assertEqual(o, "I %d %d %d %d %d %d %d %d %d\n" % (V, T, D, H, HKV, F, L, h0["P"], h0["flags"])) |
| 1146 | self.assertBitsEqual(h2["p"], [f32r(x) for x in h0["p"]], "reimport p == f32(orig p)") |
| 1147 | # idempotent second export |
| 1148 | out2 = self.path("hx2") |
| 1149 | self.ix("export-hf", ck2, out2) |
| 1150 | self.assertEqual(rb(os.path.join(out2, "model.safetensors")), st) |
| 1151 | self.assertEqual(jload((os.path.join(out2, "config.json"))), cfg) |
| 1152 | # bf16 straight from f64 weights (single RNE) |
| 1153 | self.check_export(ck, self.path("hxb"), "bf16") |
| 1154 | return h0 |
| 1155 | |
| 1156 | def test_helix_gpt_loop(self): |
| 1157 | self._helix("gpt", 256, 16, 2, 2, 32, 3, 16, extra=(10000000, 0, 100, 1, 1, 3)) |
| 1158 | |
| 1159 | def test_helix_swiglu_wpe_untied(self): |
| 1160 | self._helix("6", 70, 16, 4, 2, 24, 2, 12) |
| 1161 | |
| 1162 | def test_helix_rope_relu(self): |
| 1163 | self._helix("1", 64, 16, 4, 4, 20, 2, 8) |
| 1164 | |
| 1165 | def test_helix_gelu_rope_qkn_untied(self): |
| 1166 | self._helix("45", 64, 16, 4, 2, 20, 2, 8) |
| 1167 | |
| 1168 | def test_llama_preset_with_loop_is_helix(self): |
| 1169 | self._helix("llama", 64, 16, 4, 2, 24, 3, 8, extra=(500000000, 100000, 100, 1, 1, 2)) |
| 1170 | |
| 1171 | def test_tied_gemma_preset_is_helix(self): |
| 1172 | self._helix("gemma", 64, 16, 4, 2, 24, 2, 8) |
| 1173 | |
| 1174 | def test_univ_llama_preset_is_llama(self): |
| 1175 | self._helix("llama", 64, 16, 4, 2, 24, 2, 8, want_mt="llama") |
| 1176 | |
| 1177 | def test_univ_qwen3_preset_is_qwen3(self): |
| 1178 | self._helix("qwen3", 300, 16, 4, 2, 24, 2, 8, want_mt="qwen3") |
| 1179 | |
| 1180 | |
| 1181 | # ----------------------------------------------------------------------------- export-gguf |
| 1182 | |
| 1183 | @unittest.skipUnless(HAVE_IX, "ollm-interchange not built (%s)" % IX_BIN) |
| 1184 | class T30GGUF(Base): |
| 1185 | |
| 1186 | def check_gguf(self, ck): |
| 1187 | h = ck4_read(ck) |
| 1188 | mt, want = ck_to_hf(h, gguf=True) |
| 1189 | gp = self.path("m.gguf") |
| 1190 | o = self.ix("export-gguf", ck, gp) |
| 1191 | b = rb(gp) |
| 1192 | self.assertEqual(o, "XG %d %d\n" % (len(want), len(b))) |
| 1193 | g = gguf_parse(b) |
| 1194 | self.assertEqual(g["magic"], GGUF_MAGIC) |
| 1195 | self.assertEqual(b[:4], b"GGUF") |
| 1196 | self.assertEqual(g["version"], 3) |
| 1197 | self.assertEqual(g["nt"], len(want)) |
| 1198 | self.assertEqual(g["nkv"], 20) |
| 1199 | kv = g["kvs"] |
| 1200 | arch = mt |
| 1201 | D, H, E = h["D"], h["H"], h["D"] // h["H"] |
| 1202 | U32, F32, STR = 4, 6, 8 |
| 1203 | exp = OrderedDict([ |
| 1204 | ("general.architecture", (STR, arch)), ("general.name", (STR, "omega-helix")), |
| 1205 | ("general.alignment", (U32, 32)), ("general.file_type", (U32, 0)), |
| 1206 | (arch + ".vocab_size", (U32, h["V"])), (arch + ".context_length", (U32, h["T"])), |
| 1207 | (arch + ".embedding_length", (U32, D)), (arch + ".block_count", (U32, h["L"])), |
| 1208 | (arch + ".feed_forward_length", (U32, h["F"])), (arch + ".attention.head_count", (U32, H)), |
| 1209 | (arch + ".attention.head_count_kv", (U32, h["HKV"])), (arch + ".attention.key_length", (U32, E)), |
| 1210 | (arch + ".attention.value_length", (U32, E)), |
| 1211 | (arch + ".attention.layer_norm_rms_epsilon", (F32, f32r(struct.unpack("<d", struct.pack("<Q", h["eps_bits"]))[0]))), |
| 1212 | (arch + ".rope.freq_base", (F32, f32r(h["theta_milli"] / 1000.0))), |
| 1213 | (arch + ".rope.dimension_count", (U32, E)), |
| 1214 | ("helix.arch_flags", (U32, h["flags"])), ("helix.loop.lp", (U32, h["LP"])), |
| 1215 | ("helix.loop.lc", (U32, h["LC"])), ("helix.loop.np", (U32, h["NP"])), |
| 1216 | ]) |
| 1217 | self.assertEqual(set(kv), set(exp), "GGUF KV key set") |
| 1218 | for k, v in exp.items(): |
| 1219 | self.assertEqual(kv[k], v, "GGUF KV %s" % k) |
| 1220 | # tensors |
| 1221 | ds = (g["info_end"] + 31) // 32 * 32 |
| 1222 | self.assertEqual([t[0] for t in g["tensors"]], [gguf_name(w[0]) for w in want], "GGUF tensor names/order") |
| 1223 | end = 0 |
| 1224 | for (name, dims, typ, off), (hn, shape, vals) in zip(g["tensors"], want): |
| 1225 | self.assertEqual(typ, 0, name) |
| 1226 | self.assertEqual(dims, list(reversed(shape)), "%s ggml dims" % name) |
| 1227 | self.assertEqual(off % 32, 0, "%s offset not 32-aligned" % name) |
| 1228 | self.assertGreaterEqual(off, end, "%s overlaps previous tensor" % name) |
| 1229 | self.assertLess(off - end, 32 if end else 1, "%s gap beyond alignment padding" % name) |
| 1230 | if arch == "llama" and hn.endswith("q_proj.weight"): |
| 1231 | vals = llama_permute(vals, shape[0], shape[1], H) |
| 1232 | if arch == "llama" and hn.endswith("k_proj.weight"): |
| 1233 | vals = llama_permute(vals, shape[0], shape[1], h["HKV"]) |
| 1234 | raw = b[ds + off: ds + off + 4 * len(vals)] |
| 1235 | self.assertEqual(raw, struct.pack("<%df" % len(vals), *vals), "%s F32 data" % name) |
| 1236 | end = off + 4 * len(vals) |
| 1237 | self.assertEqual(len(b), ds + end, "GGUF must end at end of last tensor") |
| 1238 | return g, mt |
| 1239 | |
| 1240 | def _hf(self, kind, V, tied=None, want=None): |
| 1241 | m = HFModel(kind, V, tied=tied, seed=41) |
| 1242 | cp, sp = m.write(self.path("hf")) |
| 1243 | ck = self.path("a.ck") |
| 1244 | self.ix("import-hf", cp, sp, ck) |
| 1245 | g, mt = self.check_gguf(ck) |
| 1246 | self.assertEqual(mt, want or kind) |
| 1247 | return g |
| 1248 | |
| 1249 | def test_llama_tied(self): |
| 1250 | g = self._hf("llama", 96, tied=True) |
| 1251 | self.assertNotIn("output.weight", [t[0] for t in g["tensors"]]) |
| 1252 | |
| 1253 | def test_llama_untied_permute(self): |
| 1254 | g = self._hf("llama", 64, tied=False) |
| 1255 | self.assertIn("output.weight", [t[0] for t in g["tensors"]]) |
| 1256 | |
| 1257 | def test_qwen3(self): |
| 1258 | self._hf("qwen3", 300, tied=False) |
| 1259 | |
| 1260 | def test_gemma(self): |
| 1261 | g = self._hf("gemma", 80) |
| 1262 | self.assertNotIn("output.weight", [t[0] for t in g["tensors"]]) |
| 1263 | |
| 1264 | @unittest.skipUnless(HAVE_UNIV, "ollm-univ missing") |
| 1265 | def test_helix_loop_wpe(self): |
| 1266 | ck = self.path("u.ck") |
| 1267 | self.univ("init", ck, "gpt", 256, 16, 16, 2, 2, 32, 3, 1, 0, 1000, 100, 10000000, 0, 100, 1, 1, 3) |
| 1268 | g, mt = self.check_gguf(ck) |
| 1269 | self.assertEqual(mt, "helix") |
| 1270 | self.assertIn("position_embd.weight", [t[0] for t in g["tensors"]]) |
| 1271 | |
| 1272 | @unittest.skipUnless(HAVE_UNIV, "ollm-univ missing") |
| 1273 | def test_helix_untied_swiglu(self): |
| 1274 | ck = self.path("u.ck") |
| 1275 | self.univ("init", ck, "6", 70, 12, 16, 4, 2, 24, 2, 1, 0, 1000, 100) |
| 1276 | g, mt = self.check_gguf(ck) |
| 1277 | self.assertEqual(mt, "helix") |
| 1278 | self.assertIn("output.weight", [t[0] for t in g["tensors"]]) |
| 1279 | |
| 1280 | |
| 1281 | # ----------------------------------------------------------------------------- upgrade legacy |
| 1282 | |
| 1283 | LEG = dict(V=256, T=16, D=16, H=2, F=32, B=2) |
| 1284 | |
| 1285 | |
| 1286 | @unittest.skipUnless(HAVE_IX and HAVE_LEGACY and HAVE_UNIV, "needs ollm-interchange, ollm-macos, ollm-univ") |
| 1287 | class T40Upgrade(Base): |
| 1288 | |
| 1289 | def corpus(self): |
| 1290 | rng = random.Random(9) |
| 1291 | w = ("the quick brown fox jumps over a lazy dog while omega helix trains seven small " |
| 1292 | "models on bytes and every story ends here").split() |
| 1293 | tr, he = self.path("train.bin"), self.path("held.bin") |
| 1294 | wb(tr, " ".join(rng.choice(w) for _ in range(3000)).encode()) |
| 1295 | wb(he, " ".join(rng.choice(w) for _ in range(600)).encode()) |
| 1296 | return tr, he |
| 1297 | |
| 1298 | def _up(self, ver, L, extra, steps=3): |
| 1299 | tr, he = self.corpus() |
| 1300 | ck = self.path("leg.ck") |
| 1301 | r, o, e = run(LEGACY_BIN, "init", ck, LEG["V"], LEG["T"], LEG["D"], LEG["H"], LEG["F"], L, LEG["B"], |
| 1302 | 7, 50, 3000, *extra) |
| 1303 | self.assertEqual(r, 0, o + e) |
| 1304 | r, o, e = run(LEGACY_BIN, "train", ck, tr, steps, steps) |
| 1305 | self.assertEqual(r, 0, o + e) |
| 1306 | lh = legacy_read(ck) |
| 1307 | self.assertEqual(lh["ver"], ver) |
| 1308 | self.assertEqual(lh["step"], steps) |
| 1309 | up = self.path("up.ck") |
| 1310 | o = self.ix("upgrade", ck, up) |
| 1311 | self.assertEqual(o, "U %d %d\n" % (ver, lh["P"])) |
| 1312 | h = ck4_read(up) |
| 1313 | exp = dict(V=256, T=LEG["T"], D=LEG["D"], H=LEG["H"], HKV=LEG["H"], F=LEG["F"], L=L, B=LEG["B"], seed=7, |
| 1314 | step=steps, total=50, lr_bits=lh["lr_bits"], P=lh["P"], flags=0, eps_bits=f64bits(1e-5)) |
| 1315 | for k, v in exp.items(): |
| 1316 | self.assertEqual(h[k], v, "upgraded header %s" % k) |
| 1317 | if ver == 3: |
| 1318 | self.assertEqual(lp_lc_np(h), (lh["LP"], lh["LC"], lh["NP"])) |
| 1319 | else: |
| 1320 | self.assertEqual((h["LP"], h["LC"]), (0, 0)) |
| 1321 | self.assertIn(h["NP"], (0, 1)) |
| 1322 | self.assertEqual(h["raw"][208:], lh["payload"], "p/m/v not copied bit-exact") |
| 1323 | for W in (1, 4, 10): |
| 1324 | r1, o1, e1 = run(LEGACY_BIN, "eval", ck, he, W) |
| 1325 | self.assertEqual(r1, 0, o1 + e1) |
| 1326 | o2 = self.univ("eval", up, he, W) |
| 1327 | self.assertEqual(o2, o1, "eval parity W=%d legacy %r univ %r" % (W, o1, o2)) |
| 1328 | # upgraded checkpoints export as helix models |
| 1329 | mt, _ = ck_to_hf(h) |
| 1330 | self.assertEqual(mt, "helix") |
| 1331 | return ck, up |
| 1332 | |
| 1333 | def test_ck01(self): |
| 1334 | self._up(1, 2, ()) |
| 1335 | |
| 1336 | def test_ck02(self): |
| 1337 | self._up(2, 2, (2,)) |
| 1338 | |
| 1339 | def test_ck03_loop(self): |
| 1340 | self._up(3, 3, (1, 1, 1, 3)) |
| 1341 | |
| 1342 | def test_upgraded_trains_in_univ(self): |
| 1343 | ck, up = self._up(1, 2, (), steps=2) |
| 1344 | tr, _ = self.corpus() |
| 1345 | o = self.univ("train", up, tr, 3, 1) |
| 1346 | self.assertTrue(o.startswith("T 3 "), o) |
| 1347 | |
| 1348 | def _continued(self, ver, L, extra): |
| 1349 | """Training continued after upgrade matches the legacy engine line for line.""" |
| 1350 | ck, up = self._up(ver, L, extra, steps=3) |
| 1351 | tr, he = self.corpus() |
| 1352 | r, o1, e1 = run(LEGACY_BIN, "train", ck, tr, 8, 1) |
| 1353 | self.assertEqual(r, 0, o1 + e1) |
| 1354 | o2 = self.univ("train", up, tr, 8, 1) |
| 1355 | self.assertEqual(len(o1.splitlines()), 5, o1) |
| 1356 | self.assertEqual(o2, o1, "continued train T lines: legacy %r univ %r" % (o1, o2)) |
| 1357 | r, e1, _ = run(LEGACY_BIN, "eval", ck, he, 6) |
| 1358 | self.assertEqual(r, 0) |
| 1359 | self.assertEqual(self.univ("eval", up, he, 6), e1, "eval after continued training") |
| 1360 | # the two engines sum gradients in different orders, so after continued training the |
| 1361 | # parameters agree to rounding (not bit for bit); the printed T and E lines are identical |
| 1362 | P = legacy_read(ck)["P"] |
| 1363 | a = struct.unpack_from("<%dd" % P, rb(up), 208) |
| 1364 | b = struct.unpack_from("<%dd" % P, legacy_read(ck)["payload"], 0) |
| 1365 | mx = max(abs(x - y) / max(abs(x), abs(y), 1e-30) for x, y in zip(a, b)) |
| 1366 | self.assertLess(mx, 1e-9, "params after continued training: max rel diff %.3e" % mx) |
| 1367 | |
| 1368 | def test_continued_training_ck01(self): |
| 1369 | self._continued(1, 2, ()) |
| 1370 | |
| 1371 | def test_continued_training_ck03_loop(self): |
| 1372 | self._continued(3, 3, (1, 1, 1, 3)) |
| 1373 | |
| 1374 | def test_upgrade_refusals(self): |
| 1375 | ck, up = self._up(1, 2, (), steps=1) |
| 1376 | b = bytearray(rb(ck)) |
| 1377 | bad = self.path("bad.ck") |
| 1378 | c = bytearray(b) |
| 1379 | c[0] ^= 0xFF |
| 1380 | wb(bad, c) |
| 1381 | self.ix("upgrade", bad, self.path("x.ck"), rc=11) |
| 1382 | c = bytearray(b) |
| 1383 | c[-5] ^= 0x01 |
| 1384 | wb(bad, c) |
| 1385 | self.ix("upgrade", bad, self.path("x.ck"), rc=14) |
| 1386 | wb(bad, b[:-8]) |
| 1387 | self.ix("upgrade", bad, self.path("x.ck"), rc=10) |
| 1388 | wb(bad, b + b"\0") |
| 1389 | self.ix("upgrade", bad, self.path("x.ck"), rc=15) |
| 1390 | wb(bad, b[:50]) |
| 1391 | self.ix("upgrade", bad, self.path("x.ck"), rc=10) |
| 1392 | self.ix("upgrade", up, self.path("x.ck"), rc=11) # CK04 is not a legacy checkpoint |
| 1393 | self.assertFalse(os.path.exists(self.path("x.ck"))) |
| 1394 | |
| 1395 | |
| 1396 | # ----------------------------------------------------------------------------- negative controls |
| 1397 | |
| 1398 | @unittest.skipUnless(HAVE_IX, "ollm-interchange not built (%s)" % IX_BIN) |
| 1399 | class T50Refusals(Base): |
| 1400 | |
| 1401 | def setUp(self): |
| 1402 | super().setUp() |
| 1403 | self.m = HFModel("llama", 64, tied=False, seed=51) |
| 1404 | |
| 1405 | def imp(self, rc, cfg=None, tensors=None, st=None, model=None, sub="n"): |
| 1406 | m = model or self.m |
| 1407 | cp, sp = m.write(self.path(sub), cfg=cfg, tensors=tensors, st=st) |
| 1408 | ck = self.path(sub + ".ck") |
| 1409 | self.ix("import-hf", cp, sp, ck, rc=rc) |
| 1410 | if rc != 0: |
| 1411 | self.assertFalse(os.path.exists(ck), "refused import left %s behind" % ck) |
| 1412 | |
| 1413 | def cfg(self, **kw): |
| 1414 | c = self.m.config() |
| 1415 | for k, v in kw.items(): |
| 1416 | if v is KeyError: |
| 1417 | c.pop(k, None) |
| 1418 | else: |
| 1419 | c[k] = v |
| 1420 | return c |
| 1421 | |
| 1422 | def test_positive_control(self): |
| 1423 | self.imp(0) |
| 1424 | |
| 1425 | def test_usage_2(self): |
| 1426 | self.ix(rc=2) |
| 1427 | self.ix("bogus", rc=2) |
| 1428 | self.ix("import-hf", "a", "b", rc=2) |
| 1429 | self.ix("import-hf", "a", "b", "c", "1", rc=2) |
| 1430 | self.ix("export-hf", "a", rc=2) |
| 1431 | self.ix("export-gguf", "a", rc=2) |
| 1432 | self.ix("upgrade", "a", rc=2) |
| 1433 | |
| 1434 | def test_io_70(self): |
| 1435 | cp, sp = self.m.write(self.path("ok")) |
| 1436 | self.ix("import-hf", self.path("nope.json"), sp, self.path("x.ck"), rc=70) |
| 1437 | self.ix("import-hf", cp, self.path("nope.st"), self.path("x.ck"), rc=70) |
| 1438 | self.ix("import-hf", cp, sp, self.path("nodir", "sub", "x.ck"), rc=70) |
| 1439 | ck = self.path("ok.ck") |
| 1440 | self.ix("import-hf", cp, sp, ck) |
| 1441 | self.ix("export-gguf", ck, self.path("nodir", "sub", "x.gguf"), rc=70) |
| 1442 | self.ix("export-hf", ck, self.path("nodir", "sub"), rc=70, mkdir=False) |
| 1443 | self.ix("export-hf", self.path("missing.ck"), self.path("o"), rc=70) |
| 1444 | |
| 1445 | def test_json_80(self): |
| 1446 | self.imp(80, cfg='{"model_type": "llama", "vocab_size": 64,') |
| 1447 | self.imp(80, cfg="not json at all") |
| 1448 | self.imp(80, cfg='{"model_type": "llama"} trailing') |
| 1449 | |
| 1450 | def test_config_81(self): |
| 1451 | for k in ("vocab_size", "hidden_size", "intermediate_size", "num_hidden_layers", "num_attention_heads"): |
| 1452 | with self.subTest(missing=k): |
| 1453 | self.imp(81, cfg=self.cfg(**{k: KeyError}), sub="m" + k) |
| 1454 | self.imp(81, cfg=self.cfg(model_type="bert"), sub="bert") |
| 1455 | self.imp(81, cfg=self.cfg(model_type=KeyError), sub="nomt") |
| 1456 | self.imp(81, cfg=self.cfg(vocab_size="64"), sub="strv") |
| 1457 | self.imp(81, cfg=self.cfg(hidden_size=-16), sub="neg") |
| 1458 | cp, sp = self.m.write(self.path("arr"), cfg="[1, 2, 3]") # valid JSON, not an object |
| 1459 | r, o, e = run(IX_BIN, "import-hf", cp, sp, self.path("arr.ck")) |
| 1460 | self.assertIn(r, (80, 81), "non-object config.json -> rc %d" % r) |
| 1461 | |
| 1462 | def test_unsupported_82(self): |
| 1463 | self.imp(82, cfg=self.cfg(rope_scaling={"type": "linear", "factor": 2.0}), sub="rs") |
| 1464 | self.imp(82, cfg=self.cfg(head_dim=8), sub="hd") |
| 1465 | self.imp(82, cfg=self.cfg(hidden_act="gelu"), sub="act") |
| 1466 | mi = HFModel("mistral", 64, tied=False, seed=52) |
| 1467 | c = mi.config() |
| 1468 | c["sliding_window"] = 4 |
| 1469 | self.imp(82, cfg=c, model=mi, sub="sw") |
| 1470 | c["sliding_window"] = 4096 |
| 1471 | self.imp(0, cfg=c, model=mi, sub="swok") |
| 1472 | ts = self.m.st_tensors() + [("model.layers.0.self_attn.q_proj.bias", "F32", [16], |
| 1473 | encode([0.0] * 15 + [0.25], "F32"))] |
| 1474 | self.imp(82, tensors=ts, sub="bias") |
| 1475 | |
| 1476 | def test_header_83(self): |
| 1477 | ts = self.m.st_tensors() |
| 1478 | good = st_bytes(ts, metadata={"format": "pt"}) |
| 1479 | n = struct.unpack_from("<Q", good, 0)[0] |
| 1480 | body = good[8 + n:] |
| 1481 | hdr = json.loads(good[8:8 + n].decode()) |
| 1482 | cases = {} |
| 1483 | cases["N1"] = struct.pack("<Q", 1) + b"{" + body |
| 1484 | cases["Nbig"] = struct.pack("<Q", 983041) + good[8:] |
| 1485 | cases["badjson"] = struct.pack("<Q", n) + (b"{" + b" " * (n - 1)) + body |
| 1486 | h2 = json.loads(json.dumps(hdr)) |
| 1487 | h2["model.norm.weight"]["dtype"] = 7 |
| 1488 | cases["badentry"] = st_bytes(ts, raw_header=json.dumps(h2).encode()) |
| 1489 | h3 = json.loads(json.dumps(hdr)) |
| 1490 | e = h3["model.norm.weight"] |
| 1491 | e["shape"] = [8] # size != numel*dtype |
| 1492 | cases["size"] = st_bytes(ts, raw_header=json.dumps(h3).encode()) |
| 1493 | h4 = json.loads(json.dumps(hdr)) |
| 1494 | e = h4["model.norm.weight"] |
| 1495 | e["data_offsets"] = [e["data_offsets"][0] - 4, e["data_offsets"][1] - 4] # overlap |
| 1496 | cases["overlap"] = st_bytes(ts, raw_header=json.dumps(h4).encode()) |
| 1497 | cases["trailing"] = good + b"\0" * 8 |
| 1498 | hh = json.loads(json.dumps(hdr)) |
| 1499 | last = max((v["data_offsets"][1] for k, v in hh.items() if k != "__metadata__")) |
| 1500 | # hole: shift lm_head (last tensor) up by 4 bytes and append 4 bytes |
| 1501 | lk = [k for k, v in hh.items() if k != "__metadata__" and v["data_offsets"][1] == last][0] |
| 1502 | hh[lk]["data_offsets"] = [hh[lk]["data_offsets"][0] + 4, last + 4] |
| 1503 | lraw = [t for t in ts if t[0] == lk][0][3] |
| 1504 | hole_body = body[:len(body) - len(lraw)] + b"\0\0\0\0" + lraw |
| 1505 | hj = json.dumps(hh).encode() |
| 1506 | hj += b" " * ((-(8 + len(hj))) % 8) |
| 1507 | cases["hole"] = struct.pack("<Q", len(hj)) + hj + hole_body |
| 1508 | js = good[8:8 + n].rstrip(b" ") |
| 1509 | dup = js[:-1] + b',"model.norm.weight":' + json.dumps(hdr["model.norm.weight"]).encode() + b"}" |
| 1510 | dup += b" " * ((-(8 + len(dup))) % 8) |
| 1511 | cases["duplicate"] = struct.pack("<Q", len(dup)) + dup + body |
| 1512 | for name, st in cases.items(): |
| 1513 | with self.subTest(case=name): |
| 1514 | self.imp(83, st=st, sub="h" + name) |
| 1515 | |
| 1516 | def test_tensor_84(self): |
| 1517 | ts = self.m.st_tensors() |
| 1518 | self.imp(84, tensors=[t for t in ts if t[0] != "model.norm.weight"], sub="missing") |
| 1519 | self.imp(84, tensors=[t for t in ts if t[0] != "lm_head.weight"], sub="nolmh") |
| 1520 | self.imp(84, tensors=ts + [("model.foo.weight", "F32", [2], encode([1.0, 2.0], "F32"))], sub="unk") |
| 1521 | self.imp(84, tensors=ts + [("model.layers.2.input_layernorm.weight", "F32", [16], |
| 1522 | encode([1.0] * 16, "F32"))], sub="layer2") |
| 1523 | bad = [(n, ("I32" if n == "model.norm.weight" else d), s, r) for n, d, s, r in ts] |
| 1524 | self.imp(84, tensors=bad, sub="i32") |
| 1525 | bad = [(n, ("F8_E4M3" if n == "model.norm.weight" else d), s, |
| 1526 | (r[:16] if n == "model.norm.weight" else r)) for n, d, s, r in ts] |
| 1527 | self.imp(84, tensors=bad, sub="f8") |
| 1528 | |
| 1529 | def test_shape_85(self): |
| 1530 | ts = self.m.st_tensors() |
| 1531 | k = "model.layers.0.self_attn.k_proj.weight" |
| 1532 | self.imp(85, tensors=[(n, d, ([16, 8] if n == k else s), r) for n, d, s, r in ts], sub="kT") |
| 1533 | g = "model.layers.1.mlp.gate_proj.weight" |
| 1534 | self.imp(85, tensors=[(n, d, ([16, 24] if n == g else s), r) for n, d, s, r in ts], sub="gT") |
| 1535 | e = "model.embed_tokens.weight" |
| 1536 | self.imp(85, tensors=[(n, d, ([16, 64] if n == e else s), r) for n, d, s, r in ts], sub="eT") |
| 1537 | nn = "model.norm.weight" |
| 1538 | self.imp(85, tensors=[(n, d, ([4, 4] if n == nn else s), r) for n, d, s, r in ts], sub="n2d") |
| 1539 | |
| 1540 | def test_nonfinite_86(self): |
| 1541 | for dt in ("F32", "BF16", "F16", "F64"): |
| 1542 | for bad in (float("nan"), float("inf"), float("-inf")): |
| 1543 | with self.subTest(dtype=dt, v=bad): |
| 1544 | m = HFModel("llama", 64, tied=False, seed=53, dtype=dt) |
| 1545 | name = "model.layers.1.mlp.down_proj.weight" |
| 1546 | shape, vals = m.t[name] |
| 1547 | vals = list(vals) |
| 1548 | vals[7] = bad |
| 1549 | m.t[name] = (shape, vals) |
| 1550 | self.imp(86, model=m, sub="nf%s%r" % (dt, bad)) |
| 1551 | |
| 1552 | def test_truncated_87(self): |
| 1553 | good = st_bytes(self.m.st_tensors(), metadata={"format": "pt"}) |
| 1554 | n = struct.unpack_from("<Q", good, 0)[0] |
| 1555 | for name, cut in (("tail", good[:-10]), ("half", good[:8 + n + 100]), ("hdronly", good[:8 + n]), |
| 1556 | ("midhdr", good[:8 + n // 2]), ("4bytes", good[:4]), ("empty", b"")): |
| 1557 | with self.subTest(case=name): |
| 1558 | self.imp(87, st=cut, sub="t" + name) |
| 1559 | |
| 1560 | def test_geometry_88(self): |
| 1561 | self.imp(88, cfg=self.cfg(num_key_value_heads=3), sub="hkv3") |
| 1562 | self.imp(88, cfg=self.cfg(num_key_value_heads=8), sub="hkv8") |
| 1563 | self.imp(88, cfg=self.cfg(hidden_size=18, head_dim=KeyError), sub="dmodh") |
| 1564 | |
| 1565 | def test_helix_tie_mismatch_81(self): |
| 1566 | if not HAVE_UNIV: |
| 1567 | self.skipTest("ollm-univ missing") |
| 1568 | ck = self.path("u.ck") |
| 1569 | self.univ("init", ck, "6", 70, 12, 16, 4, 2, 24, 2, 1, 0, 1000, 100) |
| 1570 | out = self.path("hx") |
| 1571 | self.ix("export-hf", ck, out) |
| 1572 | cfg = jload((os.path.join(out, "config.json"))) |
| 1573 | cfg["tie_word_embeddings"] = True |
| 1574 | cp = self.path("hx", "bad.json") |
| 1575 | wb(cp, json.dumps(cfg).encode()) |
| 1576 | self.ix("import-hf", cp, os.path.join(out, "model.safetensors"), self.path("x.ck"), rc=81) |
| 1577 | |
| 1578 | def test_ck_refusals(self): |
| 1579 | cp, sp = self.m.write(self.path("ok")) |
| 1580 | ck = self.path("ok.ck") |
| 1581 | self.ix("import-hf", cp, sp, ck) |
| 1582 | b = rb(ck) |
| 1583 | bad = self.path("bad.ck") |
| 1584 | cases = [("short", b[:100], 10), ("trunc", b[:-8], 10), ("magic", b"X" + b[1:], 11), |
| 1585 | ("geom", b[:24] + struct.pack("<Q", 0) + b[32:], 12), |
| 1586 | ("P", b[:104] + struct.pack("<Q", struct.unpack_from("<Q", b, 104)[0] + 1) + b[112:], 13), |
| 1587 | ("fnv", b[:-3] + bytes([b[-3] ^ 1]) + b[-2:], 14), ("long", b + b"\0" * 8, 15)] |
| 1588 | for name, data, rc in cases: |
| 1589 | with self.subTest(case=name): |
| 1590 | wb(bad, data) |
| 1591 | self.ix("export-hf", bad, self.path("o-" + name), rc=rc) |
| 1592 | self.ix("export-gguf", bad, self.path(name + ".gguf"), rc=rc) |
| 1593 | self.assertFalse(os.path.exists(self.path(name + ".gguf"))) |
| 1594 | |
| 1595 | |
| 1596 | if __name__ == "__main__": |
| 1597 | print("ollm-interchange: %s (%s)" % (IX_BIN, "found" if HAVE_IX else "MISSING")) |
| 1598 | print("ollm-univ: %s (%s)" % (UNIV_BIN, "found" if HAVE_UNIV else "MISSING")) |
| 1599 | print("ollm-macos: %s (%s)" % (LEGACY_BIN, "found" if HAVE_LEGACY else "MISSING")) |
| 1600 | unittest.main() |