omega-helix
This project has not described itself yet.
Brought by drakestapleton
omega-helix / tests / test_ollmbf01_dna.py
| 1 | #!/usr/bin/env python3 |
| 2 | """tests/test_ollmbf01_dna.py: stdlib-only verifier for OLLMBF01, ollm-dna, and Studio BF16 DNA integration. |
| 3 | |
| 4 | Covers: |
| 5 | 1. Pure-Omega builds (TARGET=interchange, TARGET=dna, cross-compile TARGET=dna-gb10), |
| 6 | AArch64 static ELF header verification, and zero libc/CUDA proof via otool -L / ldd. |
| 7 | 2. Multi-shard BF16 + F32->BF16 synthetic HF safetensors import with exact weight FNV-1a |
| 8 | checksum parity against an independent pure-Python BF16 reference, `info-bf16` parity, |
| 9 | and `ollm-dna` `info` / `base-eval` / `cryst` / `spinfo` / `cal-cos` / `spguard-eval`. |
| 10 | 3. Bounded streaming memory test (>= 64 MiB total weights, peak child RSS < 64 MiB). |
| 11 | 4. All 3 negative-control classes failing closed with zero finalized output: |
| 12 | (a) Truncated safetensors (<8B, hdr>size, hdr>cap, data_offsets[1]>rem, doff0>doff1, short pread) |
| 13 | (b) Header/dtype/shape mismatch (invalid JSON, missing keys, I32/I64/BOOL/F8_E4M3, bad byte len, bad shape) |
| 14 | (c) Corrupted OLLMBF01 (1-bit hdr flip rc=61, 1-bit payload flip rc=61, truncated rc=60, bad magic rc=60) |
| 15 | across `ollm-interchange info-bf16` and `ollm-dna info` / `base-eval` / `spguard-eval`. |
| 16 | 5. Omega Studio CLI `--json` (success + error) and HTTP `/api/runtime/import-hf-bf16` |
| 17 | with clean `srv.shutdown(); srv.server_close()`. |
| 18 | """ |
| 19 | |
| 20 | from __future__ import annotations |
| 21 | |
| 22 | import json |
| 23 | import os |
| 24 | import platform |
| 25 | import shutil |
| 26 | import struct |
| 27 | import subprocess |
| 28 | import sys |
| 29 | import tempfile |
| 30 | import threading |
| 31 | import unittest |
| 32 | import urllib.error |
| 33 | import urllib.request |
| 34 | from pathlib import Path |
| 35 | from typing import Any |
| 36 | |
| 37 | REPO_ROOT = Path(__file__).resolve().parent.parent |
| 38 | TOOLS_DIR = REPO_ROOT / "tools" |
| 39 | STUDIO_DIR = TOOLS_DIR / "studio" |
| 40 | for _p in (str(TOOLS_DIR), str(STUDIO_DIR)): |
| 41 | if _p not in sys.path: |
| 42 | sys.path.insert(0, _p) |
| 43 | |
| 44 | import server as studio_server # noqa: E402 |
| 45 | from runtime.hf_dna import ( # noqa: E402 |
| 46 | import_hf_bf16_trunk, |
| 47 | read_ollmbf01_header, |
| 48 | run_bf16_dna_demo, |
| 49 | verify_ollmbf01, |
| 50 | ) |
| 51 | |
| 52 | FNV_OFFSET = 14695981039346656037 |
| 53 | FNV_PRIME = 1099511628211 |
| 54 | MASK64 = (1 << 64) - 1 |
| 55 | |
| 56 | |
| 57 | def _fnv1a_bytes(data: bytes, h: int = FNV_OFFSET) -> int: |
| 58 | for b in data: |
| 59 | h = ((h ^ b) * FNV_PRIME) & MASK64 |
| 60 | return h |
| 61 | |
| 62 | |
| 63 | def _fnv1a_words64(data: bytes, h: int = FNV_OFFSET) -> int: |
| 64 | assert len(data) % 8 == 0 |
| 65 | for (w,) in struct.iter_unpack("<Q", data): |
| 66 | h = ((h ^ w) * FNV_PRIME) & MASK64 |
| 67 | return h |
| 68 | |
| 69 | |
| 70 | def _align256(n: int) -> int: |
| 71 | return ((n + 255) // 256) * 256 |
| 72 | |
| 73 | |
| 74 | def _f32_to_bf16_u16(val: float) -> int: |
| 75 | f32_b = struct.pack("<f", val) |
| 76 | bits = struct.unpack("<I", f32_b)[0] |
| 77 | exp = (bits >> 23) & 0xFF |
| 78 | if exp == 0xFF: |
| 79 | if bits & 0x7FFFFF: |
| 80 | return (bits >> 16) | 0x40 |
| 81 | return (bits >> 16) & 0xFFFF |
| 82 | lsb = (bits >> 16) & 1 |
| 83 | return ((bits + 32767 + lsb) >> 16) & 0xFFFF |
| 84 | |
| 85 | |
| 86 | def _pack_bf16_tensor(vals: list[float]) -> bytes: |
| 87 | return b"".join(struct.pack("<H", _f32_to_bf16_u16(v)) for v in vals) |
| 88 | |
| 89 | |
| 90 | def _pack_f32_tensor(vals: list[float]) -> bytes: |
| 91 | return struct.pack(f"<{len(vals)}f", *vals) |
| 92 | |
| 93 | |
| 94 | def _write_safetensors(path: Path, tensors: dict[str, tuple[str, list[int], bytes]]) -> None: |
| 95 | hdr: dict[str, Any] = {} |
| 96 | off = 0 |
| 97 | blobs: list[bytes] = [] |
| 98 | for name, (dtype, shape, raw) in tensors.items(): |
| 99 | hdr[name] = { |
| 100 | "dtype": dtype, |
| 101 | "shape": shape, |
| 102 | "data_offsets": [off, off + len(raw)], |
| 103 | } |
| 104 | off += len(raw) |
| 105 | blobs.append(raw) |
| 106 | hb = json.dumps(hdr, separators=(",", ":")).encode("utf-8") |
| 107 | while len(hb) % 8 != 0: |
| 108 | hb += b" " |
| 109 | path.write_bytes(struct.pack("<Q", len(hb)) + hb + b"".join(blobs)) |
| 110 | |
| 111 | |
| 112 | def _make_qwen3_config( |
| 113 | *, |
| 114 | V: int = 256, |
| 115 | D: int = 32, |
| 116 | H: int = 4, |
| 117 | H_kv: int = 2, |
| 118 | HD: int = 8, |
| 119 | F: int = 64, |
| 120 | L: int = 2, |
| 121 | tie: bool = False, |
| 122 | ) -> dict[str, Any]: |
| 123 | return { |
| 124 | "architectures": ["Qwen3ForCausalLM"], |
| 125 | "model_type": "qwen3", |
| 126 | "vocab_size": V, |
| 127 | "hidden_size": D, |
| 128 | "num_attention_heads": H, |
| 129 | "num_key_value_heads": H_kv, |
| 130 | "head_dim": HD, |
| 131 | "intermediate_size": F, |
| 132 | "num_hidden_layers": L, |
| 133 | "max_position_embeddings": 128, |
| 134 | "rms_norm_eps": 1e-6, |
| 135 | "rope_theta": 10000.0, |
| 136 | "tie_word_embeddings": tie, |
| 137 | } |
| 138 | |
| 139 | |
| 140 | def _build_sharded_qwen3_hf( |
| 141 | hf_dir: Path, |
| 142 | *, |
| 143 | V: int = 256, |
| 144 | D: int = 32, |
| 145 | H: int = 4, |
| 146 | H_kv: int = 2, |
| 147 | HD: int = 8, |
| 148 | F: int = 64, |
| 149 | L: int = 2, |
| 150 | tie: bool = False, |
| 151 | mixed_f32: bool = True, |
| 152 | ) -> tuple[dict[str, Any], bytes]: |
| 153 | """Build a synthetic multi-shard Qwen3 HF directory and return (config, expected_payload_bytes).""" |
| 154 | hf_dir.mkdir(parents=True, exist_ok=True) |
| 155 | cfg = _make_qwen3_config(V=V, D=D, H=H, H_kv=H_kv, HD=HD, F=F, L=L, tie=tie) |
| 156 | (hf_dir / "config.json").write_text(json.dumps(cfg, indent=2), encoding="utf-8") |
| 157 | |
| 158 | qd = H * HD |
| 159 | kvd = H_kv * HD |
| 160 | |
| 161 | def gen_vals(seed_off: int, n: int, scale: float = 0.02) -> list[float]: |
| 162 | # Exactly representable f32 values so Python & OM-2 f32->bf16 match bit-for-bit |
| 163 | return [(((i + seed_off) % 17) - 8) * scale for i in range(n)] |
| 164 | |
| 165 | shard0: dict[str, tuple[str, list[int], bytes]] = {} |
| 166 | shard1: dict[str, tuple[str, list[int], bytes]] = {} |
| 167 | weight_map: dict[str, str] = {} |
| 168 | payload_parts: list[bytes] = [] |
| 169 | |
| 170 | def add_tensor( |
| 171 | shard_idx: int, |
| 172 | name: str, |
| 173 | shape: list[int], |
| 174 | vals: list[float], |
| 175 | src_dtype: str, |
| 176 | out_dtype: str, |
| 177 | ) -> None: |
| 178 | raw_in = _pack_f32_tensor(vals) if src_dtype == "F32" else _pack_bf16_u16_list(vals) |
| 179 | raw_out = _pack_f32_tensor(vals) if out_dtype == "F32" else _pack_bf16_u16_list(vals) |
| 180 | if out_dtype == "F32" and src_dtype == "BF16": |
| 181 | # Re-unpack BF16 -> f32 for exact reference |
| 182 | raw_out = b"".join( |
| 183 | struct.pack("<I", struct.unpack("<H", raw_in[2 * i : 2 * i + 2])[0] << 16) |
| 184 | for i in range(len(vals)) |
| 185 | ) |
| 186 | pad = _align256(len(raw_out)) - len(raw_out) |
| 187 | payload_parts.append(raw_out + (b"\x00" * pad)) |
| 188 | |
| 189 | fname = f"model-0000{shard_idx + 1}-of-00002.safetensors" |
| 190 | target = shard0 if shard_idx == 0 else shard1 |
| 191 | target[name] = (src_dtype, shape, raw_in) |
| 192 | weight_map[name] = fname |
| 193 | |
| 194 | def _pack_bf16_u16_list(vals: list[float]) -> bytes: |
| 195 | return _pack_bf16_tensor(vals) |
| 196 | |
| 197 | add_tensor(0, "model.embed_tokens.weight", [V, D], gen_vals(1, V * D), "F32" if mixed_f32 else "BF16", "BF16") |
| 198 | for li in range(L): |
| 199 | sidx = 0 if li == 0 else 1 |
| 200 | pfx = f"model.layers.{li}" |
| 201 | add_tensor(sidx, f"{pfx}.input_layernorm.weight", [D], gen_vals(10 + li, D, 0.05), "BF16" if mixed_f32 else "F32", "F32") |
| 202 | add_tensor(sidx, f"{pfx}.self_attn.q_proj.weight", [qd, D], gen_vals(20 + li, qd * D), "F32" if mixed_f32 else "BF16", "BF16") |
| 203 | add_tensor(sidx, f"{pfx}.self_attn.k_proj.weight", [kvd, D], gen_vals(30 + li, kvd * D), "BF16", "BF16") |
| 204 | add_tensor(sidx, f"{pfx}.self_attn.v_proj.weight", [kvd, D], gen_vals(40 + li, kvd * D), "F32" if mixed_f32 else "BF16", "BF16") |
| 205 | add_tensor(sidx, f"{pfx}.self_attn.o_proj.weight", [D, qd], gen_vals(50 + li, D * qd), "BF16", "BF16") |
| 206 | add_tensor(sidx, f"{pfx}.self_attn.q_norm.weight", [HD], gen_vals(60 + li, HD, 0.1), "BF16" if mixed_f32 else "F32", "F32") |
| 207 | add_tensor(sidx, f"{pfx}.self_attn.k_norm.weight", [HD], gen_vals(70 + li, HD, 0.1), "F32", "F32") |
| 208 | add_tensor(sidx, f"{pfx}.post_attention_layernorm.weight", [D], gen_vals(80 + li, D, 0.05), "F32", "F32") |
| 209 | add_tensor(sidx, f"{pfx}.mlp.gate_proj.weight", [F, D], gen_vals(90 + li, F * D), "F32" if mixed_f32 else "BF16", "BF16") |
| 210 | add_tensor(sidx, f"{pfx}.mlp.up_proj.weight", [F, D], gen_vals(100 + li, F * D), "BF16", "BF16") |
| 211 | add_tensor(sidx, f"{pfx}.mlp.down_proj.weight", [D, F], gen_vals(110 + li, D * F), "BF16", "BF16") |
| 212 | |
| 213 | add_tensor(1, "model.norm.weight", [D], gen_vals(200, D, 0.05), "BF16" if mixed_f32 else "F32", "F32") |
| 214 | if not tie: |
| 215 | add_tensor(1, "lm_head.weight", [V, D], gen_vals(210, V * D), "BF16", "BF16") |
| 216 | |
| 217 | _write_safetensors(hf_dir / "model-00001-of-00002.safetensors", shard0) |
| 218 | _write_safetensors(hf_dir / "model-00002-of-00002.safetensors", shard1) |
| 219 | idx_doc = {"metadata": {"total_size": 0}, "weight_map": weight_map} |
| 220 | (hf_dir / "model.safetensors.index.json").write_text(json.dumps(idx_doc, indent=2), encoding="utf-8") |
| 221 | return cfg, b"".join(payload_parts) |
| 222 | |
| 223 | |
| 224 | def _build_single_shard_hf(hf_dir: Path, *, V: int = 256, D: int = 32, H: int = 4, H_kv: int = 2, HD: int = 8, F: int = 64, L: int = 1) -> None: |
| 225 | hf_dir.mkdir(parents=True, exist_ok=True) |
| 226 | cfg = _make_qwen3_config(V=V, D=D, H=H, H_kv=H_kv, HD=HD, F=F, L=L, tie=True) |
| 227 | (hf_dir / "config.json").write_text(json.dumps(cfg, indent=2), encoding="utf-8") |
| 228 | qd = H * HD |
| 229 | kvd = H_kv * HD |
| 230 | tensors: dict[str, tuple[str, list[int], bytes]] = {} |
| 231 | |
| 232 | def add_bf(name: str, shape: list[int]) -> None: |
| 233 | n = 1 |
| 234 | for s in shape: |
| 235 | n *= s |
| 236 | tensors[name] = ("BF16", shape, b"\x00\x3c" * n) |
| 237 | |
| 238 | add_bf("model.embed_tokens.weight", [V, D]) |
| 239 | for li in range(L): |
| 240 | pfx = f"model.layers.{li}" |
| 241 | add_bf(f"{pfx}.input_layernorm.weight", [D]) |
| 242 | add_bf(f"{pfx}.self_attn.q_proj.weight", [qd, D]) |
| 243 | add_bf(f"{pfx}.self_attn.k_proj.weight", [kvd, D]) |
| 244 | add_bf(f"{pfx}.self_attn.v_proj.weight", [kvd, D]) |
| 245 | add_bf(f"{pfx}.self_attn.o_proj.weight", [D, qd]) |
| 246 | add_bf(f"{pfx}.self_attn.q_norm.weight", [HD]) |
| 247 | add_bf(f"{pfx}.self_attn.k_norm.weight", [HD]) |
| 248 | add_bf(f"{pfx}.post_attention_layernorm.weight", [D]) |
| 249 | add_bf(f"{pfx}.mlp.gate_proj.weight", [F, D]) |
| 250 | add_bf(f"{pfx}.mlp.up_proj.weight", [F, D]) |
| 251 | add_bf(f"{pfx}.mlp.down_proj.weight", [D, F]) |
| 252 | add_bf("model.norm.weight", [D]) |
| 253 | _write_safetensors(hf_dir / "model.safetensors", tensors) |
| 254 | |
| 255 | |
| 256 | class TestOllmBf01Dna(unittest.TestCase): |
| 257 | build_dir: Path |
| 258 | ic_bin: Path |
| 259 | dna_bin: Path |
| 260 | gb10_dna_bin: Path |
| 261 | |
| 262 | @classmethod |
| 263 | def setUpClass(cls) -> None: |
| 264 | cls.build_dir = Path(tempfile.mkdtemp(prefix="ollm-bf01-test-")).resolve() |
| 265 | build_sh = REPO_ROOT / "scripts" / "build.sh" |
| 266 | for tgt in ("interchange", "dna", "dna-gb10"): |
| 267 | env = dict(os.environ, TARGET=tgt, OUT=str(cls.build_dir)) |
| 268 | proc = subprocess.run( |
| 269 | ["sh", str(build_sh)], |
| 270 | cwd=str(REPO_ROOT), |
| 271 | env=env, |
| 272 | capture_output=True, |
| 273 | text=True, |
| 274 | check=False, |
| 275 | ) |
| 276 | if proc.returncode != 0: |
| 277 | raise RuntimeError( |
| 278 | f"build.sh TARGET={tgt} failed (rc={proc.returncode}):\n{proc.stdout}\n{proc.stderr}" |
| 279 | ) |
| 280 | cls.ic_bin = cls.build_dir / "ollm-interchange" |
| 281 | cls.dna_bin = cls.build_dir / "ollm-dna" |
| 282 | cls.gb10_dna_bin = cls.build_dir / "ollm-dna-gb10" |
| 283 | |
| 284 | @classmethod |
| 285 | def tearDownClass(cls) -> None: |
| 286 | shutil.rmtree(cls.build_dir, ignore_errors=True) |
| 287 | |
| 288 | # ------------------------------------------------------------------ 1. Build & Linkage Proofs |
| 289 | |
| 290 | def test_01_static_elf_cross_compile_and_zero_libc_cuda_linkage(self) -> None: |
| 291 | # Cross-compiled GB10 AArch64 static ELF header verification |
| 292 | raw = self.gb10_dna_bin.read_bytes() |
| 293 | self.assertGreaterEqual(len(raw), 64) |
| 294 | self.assertEqual(raw[:4], b"\x7fELF") |
| 295 | ei_class = raw[4] |
| 296 | ei_data = raw[5] |
| 297 | e_type, e_machine = struct.unpack("<HH", raw[16:20]) |
| 298 | self.assertEqual(ei_class, 2) # ELF64 |
| 299 | self.assertEqual(ei_data, 1) # little-endian |
| 300 | self.assertEqual(e_type, 2) # ET_EXEC |
| 301 | self.assertEqual(e_machine, 183) # EM_AARCH64 |
| 302 | e_phoff = struct.unpack("<Q", raw[32:40])[0] |
| 303 | e_phentsize, e_phnum = struct.unpack("<HH", raw[54:58]) |
| 304 | ptypes = [ |
| 305 | struct.unpack("<I", raw[e_phoff + i * e_phentsize : e_phoff + i * e_phentsize + 4])[0] |
| 306 | for i in range(e_phnum) |
| 307 | ] |
| 308 | self.assertNotIn(3, ptypes, "ollm-dna-gb10 must have no PT_INTERP (must be static zero-libc ELF)") |
| 309 | |
| 310 | # Host binary linkage check (zero libc on Linux, only libSystem.B.dylib kernel shim on Darwin, zero CUDA) |
| 311 | system = platform.system() |
| 312 | for b in (self.ic_bin, self.dna_bin): |
| 313 | if system == "Darwin": |
| 314 | r = subprocess.run(["otool", "-L", str(b)], capture_output=True, text=True, check=True) |
| 315 | libs = [ln.strip().split(" ")[0] for ln in r.stdout.splitlines()[1:] if ln.strip()] |
| 316 | self.assertEqual(libs, ["/usr/lib/libSystem.B.dylib"], f"{b} unexpected dylibs: {libs}") |
| 317 | self.assertNotRegex(r.stdout.lower(), r"cuda|cublas|c\+\+|metal") |
| 318 | else: |
| 319 | if shutil.which("ldd"): |
| 320 | r = subprocess.run(["ldd", str(b)], capture_output=True, text=True, check=False) |
| 321 | self.assertNotRegex((r.stdout + r.stderr).lower(), r"libc\.so|libcuda|cublas") |
| 322 | |
| 323 | # ------------------------------------------------------------------ 2. Multi-shard Parity & End-to-End DNA |
| 324 | |
| 325 | def test_02_multishard_bf16_f32_parity_and_end_to_end_dna(self) -> None: |
| 326 | with tempfile.TemporaryDirectory() as td: |
| 327 | tdp = Path(td) |
| 328 | hf_dir = tdp / "hf_qwen3" |
| 329 | _, expected_payload = _build_sharded_qwen3_hf( |
| 330 | hf_dir, V=256, D=32, H=4, H_kv=2, HD=8, F=64, L=2, tie=False, mixed_f32=True, |
| 331 | ) |
| 332 | expected_wfnv = _fnv1a_words64(expected_payload) |
| 333 | |
| 334 | bf_path = tdp / "trunk.bf16" |
| 335 | imp = import_hf_bf16_trunk(self.ic_bin, hf_dir, bf_path) |
| 336 | hdr = imp["header"] |
| 337 | self.assertEqual(hdr["payload_bytes"], len(expected_payload)) |
| 338 | self.assertEqual(hdr["wfnv"], f"0x{expected_wfnv:016x}") |
| 339 | |
| 340 | # Verify payload bytes match byte-for-byte |
| 341 | actual_payload = bf_path.read_bytes()[256:] |
| 342 | self.assertEqual(actual_payload, expected_payload) |
| 343 | |
| 344 | # Parity across info-bf16 and ollm-dna info |
| 345 | ver = verify_ollmbf01(self.ic_bin, bf_path, dna_bin=self.dna_bin) |
| 346 | self.assertTrue(ver["verified"]) |
| 347 | self.assertEqual(ver["info_bf16"]["trunk_hash"], hdr["trunk_hash"]) |
| 348 | self.assertEqual(ver["dna_info"]["trunk_hash"], hdr["trunk_hash"]) |
| 349 | |
| 350 | # End-to-end ollm-dna: base-eval -> cryst (--w4 & --f64) -> spinfo -> cal-cos -> spguard-eval |
| 351 | dom_toks = [((i * 7 + 3) % 256) for i in range(64)] |
| 352 | gen_toks = [((i * 13 + 11) % 256) for i in range(64)] |
| 353 | bins = {"ollm_interchange": self.ic_bin, "ollm_dna": self.dna_bin} |
| 354 | demo_w4 = run_bf16_dna_demo( |
| 355 | bins, hf_dir, dom_toks, gen_toks, tdp / "demo_w4", fexp=16, nproto=4, epochs=3, w4=True, |
| 356 | ) |
| 357 | self.assertTrue(demo_w4["ok"]) |
| 358 | self.assertEqual(demo_w4["base_eval"]["trunk_hash"], hdr["trunk_hash"]) |
| 359 | self.assertGreater(demo_w4["base_eval"]["loss"], 0.0) |
| 360 | self.assertIn("SP_INFO V2", demo_w4["spinfo_stdout"]) |
| 361 | self.assertIn("CAL_COS TAU=", demo_w4["cal_cos_stdout"]) |
| 362 | self.assertEqual(demo_w4["spguard_eval"]["trunk_hash"], hdr["trunk_hash"]) |
| 363 | self.assertEqual(demo_w4["spguard_eval"]["dom_n"], 63) |
| 364 | self.assertEqual(demo_w4["spguard_eval"]["gen_n"], 63) |
| 365 | |
| 366 | demo_f64 = run_bf16_dna_demo( |
| 367 | bins, hf_dir, dom_toks, gen_toks, tdp / "demo_f64", fexp=16, nproto=4, epochs=2, w4=False, |
| 368 | ) |
| 369 | self.assertTrue(demo_f64["ok"]) |
| 370 | self.assertEqual(demo_f64["spguard_eval"]["trunk_hash"], hdr["trunk_hash"]) |
| 371 | |
| 372 | # ------------------------------------------------------------------ 3. Bounded Streaming Memory (>= 64 MiB) |
| 373 | |
| 374 | def test_03_bounded_rss_on_64mib_plus_sharded_import(self) -> None: |
| 375 | with tempfile.TemporaryDirectory() as td: |
| 376 | tdp = Path(td) |
| 377 | hf_dir = tdp / "hf_big" |
| 378 | hf_dir.mkdir() |
| 379 | V, D, H, H_kv, HD, F, L = 4096, 512, 8, 4, 64, 1024, 16 |
| 380 | cfg = _make_qwen3_config(V=V, D=D, H=H, H_kv=H_kv, HD=HD, F=F, L=L, tie=True) |
| 381 | (hf_dir / "config.json").write_text(json.dumps(cfg), encoding="utf-8") |
| 382 | |
| 383 | qd = H * HD |
| 384 | kvd = H_kv * HD |
| 385 | weight_map: dict[str, str] = {} |
| 386 | |
| 387 | def write_blob_shard(fname: str, specs: list[tuple[str, str, list[int]]]) -> None: |
| 388 | hdr: dict[str, Any] = {} |
| 389 | off = 0 |
| 390 | chunks: list[bytes] = [] |
| 391 | for name, dt, shape in specs: |
| 392 | n = 1 |
| 393 | for s in shape: |
| 394 | n *= s |
| 395 | nb = n * (2 if dt == "BF16" else 4) |
| 396 | hdr[name] = {"dtype": dt, "shape": shape, "data_offsets": [off, off + nb]} |
| 397 | off += nb |
| 398 | unit = b"\x00\x3c" if dt == "BF16" else b"\x00\x00\x80\x3f" |
| 399 | chunks.append(unit * n) |
| 400 | weight_map[name] = fname |
| 401 | hb = json.dumps(hdr, separators=(",", ":")).encode("utf-8") |
| 402 | while len(hb) % 8 != 0: |
| 403 | hb += b" " |
| 404 | with (hf_dir / fname).open("wb") as fh: |
| 405 | fh.write(struct.pack("<Q", len(hb))) |
| 406 | fh.write(hb) |
| 407 | for ch in chunks: |
| 408 | fh.write(ch) |
| 409 | |
| 410 | s0_specs: list[tuple[str, str, list[int]]] = [("model.embed_tokens.weight", "BF16", [V, D])] |
| 411 | s1_specs: list[tuple[str, str, list[int]]] = [] |
| 412 | for li in range(L): |
| 413 | dst = s0_specs if li < L // 2 else s1_specs |
| 414 | p = f"model.layers.{li}" |
| 415 | dst.extend([ |
| 416 | (f"{p}.input_layernorm.weight", "BF16", [D]), |
| 417 | (f"{p}.self_attn.q_proj.weight", "BF16", [qd, D]), |
| 418 | (f"{p}.self_attn.k_proj.weight", "BF16", [kvd, D]), |
| 419 | (f"{p}.self_attn.v_proj.weight", "BF16", [kvd, D]), |
| 420 | (f"{p}.self_attn.o_proj.weight", "BF16", [D, qd]), |
| 421 | (f"{p}.self_attn.q_norm.weight", "BF16", [HD]), |
| 422 | (f"{p}.self_attn.k_norm.weight", "BF16", [HD]), |
| 423 | (f"{p}.post_attention_layernorm.weight", "BF16", [D]), |
| 424 | (f"{p}.mlp.gate_proj.weight", "BF16", [F, D]), |
| 425 | (f"{p}.mlp.up_proj.weight", "BF16", [F, D]), |
| 426 | (f"{p}.mlp.down_proj.weight", "BF16", [D, F]), |
| 427 | ]) |
| 428 | s1_specs.append(("model.norm.weight", "BF16", [D])) |
| 429 | write_blob_shard("shard-00001.safetensors", s0_specs) |
| 430 | write_blob_shard("shard-00002.safetensors", s1_specs) |
| 431 | (hf_dir / "model.safetensors.index.json").write_text( |
| 432 | json.dumps({"weight_map": weight_map}), encoding="utf-8", |
| 433 | ) |
| 434 | |
| 435 | out_bf = tdp / "big.bf16" |
| 436 | meas_code = ( |
| 437 | "import os, platform, resource, subprocess, sys\n" |
| 438 | "r = subprocess.run(sys.argv[1:], capture_output=True)\n" |
| 439 | "ru = resource.getrusage(resource.RUSAGE_CHILDREN)\n" |
| 440 | "rss = ru.ru_maxrss if platform.system() == 'Darwin' else ru.ru_maxrss * 1024\n" |
| 441 | "sys.stdout.buffer.write(f'{r.returncode} {rss}\\n'.encode() + r.stdout)\n" |
| 442 | "sys.stderr.buffer.write(r.stderr)\n" |
| 443 | "sys.exit(r.returncode)\n" |
| 444 | ) |
| 445 | res = subprocess.run( |
| 446 | [sys.executable, "-c", meas_code, str(self.ic_bin), "import-hf-bf16", str(hf_dir), str(out_bf)], |
| 447 | capture_output=True, |
| 448 | text=True, |
| 449 | check=False, |
| 450 | ) |
| 451 | self.assertEqual(res.returncode, 0, res.stderr) |
| 452 | first_line, _, rest = res.stdout.partition("\n") |
| 453 | rc_s, rss_s = first_line.split() |
| 454 | self.assertEqual(int(rc_s), 0) |
| 455 | self.assertIn("IBF1 ", rest) |
| 456 | |
| 457 | hdr = read_ollmbf01_header(out_bf) |
| 458 | self.assertGreaterEqual(hdr["payload_bytes"], 64 * 1024 * 1024) |
| 459 | |
| 460 | peak_rss_bytes = int(rss_s) |
| 461 | self.assertLess( |
| 462 | peak_rss_bytes, |
| 463 | 64 * 1024 * 1024, |
| 464 | f"import-hf-bf16 peak RSS {peak_rss_bytes / (1024 * 1024):.2f} MiB exceeded 64 MiB streaming bound", |
| 465 | ) |
| 466 | |
| 467 | # ------------------------------------------------------------------ 4. Negative Controls |
| 468 | |
| 469 | def _assert_import_fails_closed(self, hf_dir: Path, out_bf: Path, desc: str) -> None: |
| 470 | if out_bf.exists(): |
| 471 | out_bf.unlink() |
| 472 | proc = subprocess.run( |
| 473 | [str(self.ic_bin), "import-hf-bf16", str(hf_dir), str(out_bf)], |
| 474 | capture_output=True, text=True, check=False, |
| 475 | ) |
| 476 | self.assertNotEqual(proc.returncode, 0, f"{desc}: expected non-zero exit code") |
| 477 | self.assertFalse(out_bf.exists(), f"{desc}: finalized output file {out_bf} must not exist on failure") |
| 478 | |
| 479 | def test_04_negative_controls_truncated_safetensors(self) -> None: |
| 480 | with tempfile.TemporaryDirectory() as td: |
| 481 | tdp = Path(td) |
| 482 | base_hf = tdp / "base" |
| 483 | _build_single_shard_hf(base_hf) |
| 484 | orig_st = (base_hf / "model.safetensors").read_bytes() |
| 485 | orig_hlen = struct.unpack("<Q", orig_st[:8])[0] |
| 486 | |
| 487 | # 1. File < 8 bytes |
| 488 | d1 = tdp / "lt8" |
| 489 | shutil.copytree(base_hf, d1) |
| 490 | (d1 / "model.safetensors").write_bytes(b"\x01\x02\x03\x04") |
| 491 | self._assert_import_fails_closed(d1, tdp / "o1.bf16", "file < 8 bytes") |
| 492 | |
| 493 | # 2. Declared header length > file size |
| 494 | d2 = tdp / "hdr_gt_sz" |
| 495 | shutil.copytree(base_hf, d2) |
| 496 | (d2 / "model.safetensors").write_bytes(struct.pack("<Q", len(orig_st) + 4096) + orig_st[8:64]) |
| 497 | self._assert_import_fails_closed(d2, tdp / "o2.bf16", "declared header > file size") |
| 498 | |
| 499 | # 3. Declared header length > cap (983040) |
| 500 | d3 = tdp / "hdr_gt_cap" |
| 501 | shutil.copytree(base_hf, d3) |
| 502 | (d3 / "model.safetensors").write_bytes(struct.pack("<Q", 1_048_576) + orig_st[8:]) |
| 503 | self._assert_import_fails_closed(d3, tdp / "o3.bf16", "declared header > cap") |
| 504 | |
| 505 | # 4. data_offsets[1] > remaining bytes (truncate 16 bytes off payload) |
| 506 | d4 = tdp / "doff1_gt_rem" |
| 507 | shutil.copytree(base_hf, d4) |
| 508 | (d4 / "model.safetensors").write_bytes(orig_st[:-16]) |
| 509 | self._assert_import_fails_closed(d4, tdp / "o4.bf16", "data_offsets[1] > remaining bytes") |
| 510 | |
| 511 | # 5. data_offsets[0] > data_offsets[1] |
| 512 | d5 = tdp / "doff0_gt_doff1" |
| 513 | shutil.copytree(base_hf, d5) |
| 514 | hdr_obj = json.loads(orig_st[8 : 8 + orig_hlen].decode("utf-8")) |
| 515 | first_k = next(iter(hdr_obj)) |
| 516 | b0, b1 = hdr_obj[first_k]["data_offsets"] |
| 517 | hdr_obj[first_k]["data_offsets"] = [b1, b0] |
| 518 | hb = json.dumps(hdr_obj, separators=(",", ":")).encode("utf-8") |
| 519 | (d5 / "model.safetensors").write_bytes(struct.pack("<Q", len(hb)) + hb + orig_st[8 + orig_hlen :]) |
| 520 | self._assert_import_fails_closed(d5, tdp / "o5.bf16", "data_offsets[0] > data_offsets[1]") |
| 521 | |
| 522 | # 6. Short pread (declared header length matches truncated header bytes at EOF) |
| 523 | d6 = tdp / "short_pread" |
| 524 | shutil.copytree(base_hf, d6) |
| 525 | (d6 / "model.safetensors").write_bytes(orig_st[: 8 + orig_hlen - 4]) |
| 526 | self._assert_import_fails_closed(d6, tdp / "o6.bf16", "short pread") |
| 527 | |
| 528 | def test_05_negative_controls_header_dtype_shape_mismatch(self) -> None: |
| 529 | with tempfile.TemporaryDirectory() as td: |
| 530 | tdp = Path(td) |
| 531 | base_hf = tdp / "base" |
| 532 | _build_single_shard_hf(base_hf) |
| 533 | orig_st = (base_hf / "model.safetensors").read_bytes() |
| 534 | orig_hlen = struct.unpack("<Q", orig_st[:8])[0] |
| 535 | orig_hdr = json.loads(orig_st[8 : 8 + orig_hlen].decode("utf-8")) |
| 536 | orig_blob = orig_st[8 + orig_hlen :] |
| 537 | |
| 538 | # 1. Invalid JSON (config.json and safetensors header) |
| 539 | d_bad_cfg = tdp / "bad_cfg_json" |
| 540 | shutil.copytree(base_hf, d_bad_cfg) |
| 541 | (d_bad_cfg / "config.json").write_text("{not valid json", encoding="utf-8") |
| 542 | self._assert_import_fails_closed(d_bad_cfg, tdp / "m1.bf16", "invalid config.json") |
| 543 | |
| 544 | d_bad_st = tdp / "bad_st_json" |
| 545 | shutil.copytree(base_hf, d_bad_st) |
| 546 | bad_hb = b"{broken json" |
| 547 | (d_bad_st / "model.safetensors").write_bytes(struct.pack("<Q", len(bad_hb)) + bad_hb + orig_blob) |
| 548 | self._assert_import_fails_closed(d_bad_st, tdp / "m2.bf16", "invalid safetensors JSON") |
| 549 | |
| 550 | # 2. Missing required keys (config key, entry key, missing tensor) |
| 551 | d_miss_cfg = tdp / "miss_cfg" |
| 552 | shutil.copytree(base_hf, d_miss_cfg) |
| 553 | cfg_m = json.loads((d_miss_cfg / "config.json").read_text(encoding="utf-8")) |
| 554 | del cfg_m["hidden_size"] |
| 555 | (d_miss_cfg / "config.json").write_text(json.dumps(cfg_m), encoding="utf-8") |
| 556 | self._assert_import_fails_closed(d_miss_cfg, tdp / "m3.bf16", "missing hidden_size in config.json") |
| 557 | |
| 558 | d_miss_ent = tdp / "miss_ent" |
| 559 | shutil.copytree(base_hf, d_miss_ent) |
| 560 | hdr_m = json.loads(json.dumps(orig_hdr)) |
| 561 | del hdr_m["model.norm.weight"]["shape"] |
| 562 | hb_m = json.dumps(hdr_m, separators=(",", ":")).encode("utf-8") |
| 563 | (d_miss_ent / "model.safetensors").write_bytes(struct.pack("<Q", len(hb_m)) + hb_m + orig_blob) |
| 564 | self._assert_import_fails_closed(d_miss_ent, tdp / "m4.bf16", "missing shape in safetensors entry") |
| 565 | |
| 566 | d_miss_ten = tdp / "miss_ten" |
| 567 | shutil.copytree(base_hf, d_miss_ten) |
| 568 | hdr_t = json.loads(json.dumps(orig_hdr)) |
| 569 | off0, off1 = hdr_t.pop("model.norm.weight")["data_offsets"] |
| 570 | # Trim matching bytes from blob and update offsets? Simpler: drop final tensor at end of blob |
| 571 | hb_t = json.dumps(hdr_t, separators=(",", ":")).encode("utf-8") |
| 572 | (d_miss_ten / "model.safetensors").write_bytes(struct.pack("<Q", len(hb_t)) + hb_t + orig_blob[:off0]) |
| 573 | self._assert_import_fails_closed(d_miss_ten, tdp / "m5.bf16", "missing required tensor model.norm.weight") |
| 574 | |
| 575 | # 3. Unsupported dtypes (I32, I64, BOOL, F8_E4M3) |
| 576 | for dt in ("I32", "I64", "BOOL", "F8_E4M3"): |
| 577 | d_dt = tdp / f"dt_{dt}" |
| 578 | shutil.copytree(base_hf, d_dt) |
| 579 | hdr_dt = json.loads(json.dumps(orig_hdr)) |
| 580 | hdr_dt["model.norm.weight"]["dtype"] = dt |
| 581 | hb_dt = json.dumps(hdr_dt, separators=(",", ":")).encode("utf-8") |
| 582 | (d_dt / "model.safetensors").write_bytes(struct.pack("<Q", len(hb_dt)) + hb_dt + orig_blob) |
| 583 | self._assert_import_fails_closed(d_dt, tdp / f"dt_{dt}.bf16", f"unsupported dtype {dt}") |
| 584 | |
| 585 | # 4. Byte length disagreeing with numel * elem_bytes |
| 586 | d_blen = tdp / "bad_blen" |
| 587 | shutil.copytree(base_hf, d_blen) |
| 588 | hdr_bl = json.loads(json.dumps(orig_hdr)) |
| 589 | b0, b1 = hdr_bl["model.norm.weight"]["data_offsets"] |
| 590 | hdr_bl["model.norm.weight"]["data_offsets"] = [b0, b1 - 2] |
| 591 | hb_bl = json.dumps(hdr_bl, separators=(",", ":")).encode("utf-8") |
| 592 | (d_blen / "model.safetensors").write_bytes(struct.pack("<Q", len(hb_bl)) + hb_bl + orig_blob[:-2]) |
| 593 | self._assert_import_fails_closed(d_blen, tdp / "m6.bf16", "byte length disagreeing with numel*elem_bytes") |
| 594 | |
| 595 | # 5. Tensor shape disagreeing with config.json (V, D, H/H_kv, F, L) |
| 596 | for field, bad_val in (("vocab_size", 128), ("hidden_size", 64), ("num_attention_heads", 8), ("num_key_value_heads", 4), ("intermediate_size", 128), ("num_hidden_layers", 2)): |
| 597 | d_sh = tdp / f"bad_cfg_{field}" |
| 598 | shutil.copytree(base_hf, d_sh) |
| 599 | c_sh = json.loads((d_sh / "config.json").read_text(encoding="utf-8")) |
| 600 | c_sh[field] = bad_val |
| 601 | (d_sh / "config.json").write_text(json.dumps(c_sh), encoding="utf-8") |
| 602 | self._assert_import_fails_closed(d_sh, tdp / f"sh_{field}.bf16", f"shape mismatch for {field}={bad_val}") |
| 603 | |
| 604 | def test_06_negative_controls_corrupted_ollmbf01_across_all_readers(self) -> None: |
| 605 | with tempfile.TemporaryDirectory() as td: |
| 606 | tdp = Path(td) |
| 607 | hf_dir = tdp / "hf" |
| 608 | _build_single_shard_hf(hf_dir) |
| 609 | good_bf = tdp / "good.bf16" |
| 610 | import_hf_bf16_trunk(self.ic_bin, hf_dir, good_bf) |
| 611 | |
| 612 | # Create tokens & valid .sp2 for spguard-eval negative control testing |
| 613 | dom_u32 = tdp / "dom.u32" |
| 614 | gen_u32 = tdp / "gen.u32" |
| 615 | dom_u32.write_bytes(struct.pack("<16I", *([1, 2, 3, 4] * 4))) |
| 616 | gen_u32.write_bytes(struct.pack("<16I", *([5, 6, 7, 8] * 4))) |
| 617 | sp2 = tdp / "strand.sp2" |
| 618 | subprocess.run( |
| 619 | [str(self.dna_bin), "cryst", str(good_bf), str(dom_u32), str(sp2), "--fexp", "8", "--nproto", "2", "--epochs", "1", "--w4"], |
| 620 | check=True, capture_output=True, |
| 621 | ) |
| 622 | |
| 623 | raw = bytearray(good_bf.read_bytes()) |
| 624 | |
| 625 | # Variant 1: 1-bit flip in OLLMBF01 header (offset 24, inside D field) -> rc=61 |
| 626 | hdr_flip = bytearray(raw) |
| 627 | hdr_flip[24] ^= 1 |
| 628 | p_hdr_flip = tdp / "hdr_flip.bf16" |
| 629 | p_hdr_flip.write_bytes(bytes(hdr_flip)) |
| 630 | |
| 631 | # Variant 2: 1-bit flip in OLLMBF01 payload (offset 256) -> rc=61 |
| 632 | pay_flip = bytearray(raw) |
| 633 | pay_flip[256] ^= 1 |
| 634 | p_pay_flip = tdp / "pay_flip.bf16" |
| 635 | p_pay_flip.write_bytes(bytes(pay_flip)) |
| 636 | |
| 637 | # Variant 3: Truncated OLLMBF01 -> rc=60 |
| 638 | p_trunc = tdp / "trunc.bf16" |
| 639 | p_trunc.write_bytes(bytes(raw[:-64])) |
| 640 | |
| 641 | # Variant 4: Bad magic -> rc=60 |
| 642 | bad_mag = bytearray(raw) |
| 643 | bad_mag[0] = ord("X") |
| 644 | p_mag = tdp / "bad_magic.bf16" |
| 645 | p_mag.write_bytes(bytes(bad_mag)) |
| 646 | |
| 647 | cases = [ |
| 648 | ("header_1bit_flip", p_hdr_flip, 61), |
| 649 | ("payload_1bit_flip", p_pay_flip, 61), |
| 650 | ("truncated", p_trunc, 60), |
| 651 | ("bad_magic", p_mag, 60), |
| 652 | ] |
| 653 | for label, bf_case, want_rc in cases: |
| 654 | cmds = [ |
| 655 | ("ollm-interchange info-bf16", [str(self.ic_bin), "info-bf16", str(bf_case)]), |
| 656 | ("ollm-dna info", [str(self.dna_bin), "info", str(bf_case)]), |
| 657 | ("ollm-dna base-eval", [str(self.dna_bin), "base-eval", str(bf_case), str(dom_u32)]), |
| 658 | ("ollm-dna spguard-eval", [str(self.dna_bin), "spguard-eval", str(bf_case), str(sp2), str(dom_u32), str(gen_u32)]), |
| 659 | ] |
| 660 | for cname, argv in cmds: |
| 661 | r = subprocess.run(argv, capture_output=True, text=True, check=False) |
| 662 | self.assertEqual( |
| 663 | r.returncode, want_rc, |
| 664 | f"{label} / {cname}: expected rc={want_rc}, got rc={r.returncode}\nstdout={r.stdout}\nstderr={r.stderr}", |
| 665 | ) |
| 666 | |
| 667 | # ------------------------------------------------------------------ 5. Studio CLI & HTTP Integration |
| 668 | |
| 669 | def test_07_studio_cli_json_and_http_import_hf_bf16(self) -> None: |
| 670 | with tempfile.TemporaryDirectory() as td: |
| 671 | tdp = Path(td) |
| 672 | hf_dir = tdp / "hf" |
| 673 | _build_single_shard_hf(hf_dir) |
| 674 | out_bf = tdp / "cli_out.bf16" |
| 675 | |
| 676 | env = dict( |
| 677 | os.environ, |
| 678 | OMEGA_HELIX_BIN_DIR=str(self.build_dir), |
| 679 | OLLM_INTERCHANGE_BIN=str(self.ic_bin), |
| 680 | OLLM_DNA_BIN=str(self.dna_bin), |
| 681 | ) |
| 682 | cli_bin = str(REPO_ROOT / "bin" / "omega-helix") |
| 683 | |
| 684 | # CLI success --json |
| 685 | r_ok = subprocess.run( |
| 686 | [cli_bin, "import-hf-bf16", str(hf_dir), "--out", str(out_bf), "--json"], |
| 687 | env=env, capture_output=True, text=True, check=False, |
| 688 | ) |
| 689 | self.assertEqual(r_ok.returncode, 0, r_ok.stderr) |
| 690 | doc_ok = json.loads(r_ok.stdout) |
| 691 | self.assertTrue(doc_ok["ok"]) |
| 692 | self.assertTrue(doc_ok["verification"]["verified"]) |
| 693 | self.assertTrue(out_bf.is_file()) |
| 694 | |
| 695 | # CLI failure --json (must emit valid JSON on stdout and leave no output file) |
| 696 | bad_out = tdp / "should_not_exist.bf16" |
| 697 | r_err = subprocess.run( |
| 698 | [cli_bin, "import-hf-bf16", str(tdp / "missing_hf"), "--out", str(bad_out), "--json"], |
| 699 | env=env, capture_output=True, text=True, check=False, |
| 700 | ) |
| 701 | self.assertNotEqual(r_err.returncode, 0) |
| 702 | doc_err = json.loads(r_err.stdout) |
| 703 | self.assertFalse(doc_err["ok"]) |
| 704 | self.assertTrue(doc_err["error"]) |
| 705 | self.assertFalse(bad_out.exists()) |
| 706 | |
| 707 | # HTTP endpoint /api/runtime/import-hf-bf16 |
| 708 | srv = studio_server.create_server( |
| 709 | host="127.0.0.1", port=0, workspace_dir=tdp / "ws", bin_dir=self.build_dir, |
| 710 | ) |
| 711 | th = threading.Thread(target=srv.serve_forever, kwargs={"poll_interval": 0.1}, daemon=True) |
| 712 | th.start() |
| 713 | host, port = srv.server_address[:2] |
| 714 | base = f"http://{host}:{port}" |
| 715 | try: |
| 716 | http_out = tdp / "http_out.bf16" |
| 717 | req_ok = urllib.request.Request( |
| 718 | f"{base}/api/runtime/import-hf-bf16", |
| 719 | data=json.dumps({"hf_dir": str(hf_dir), "out_path": str(http_out), "verify": True}).encode("utf-8"), |
| 720 | headers={"Content-Type": "application/json"}, |
| 721 | method="POST", |
| 722 | ) |
| 723 | with urllib.request.urlopen(req_ok, timeout=20.0) as resp: |
| 724 | self.assertEqual(resp.status, 200) |
| 725 | h_ok = json.loads(resp.read().decode("utf-8")) |
| 726 | self.assertTrue(h_ok["ok"]) |
| 727 | self.assertTrue(h_ok["verification"]["verified"]) |
| 728 | self.assertTrue(http_out.is_file()) |
| 729 | |
| 730 | # HTTP error case |
| 731 | req_bad = urllib.request.Request( |
| 732 | f"{base}/api/runtime/import-hf-bf16", |
| 733 | data=json.dumps({"hf_dir": str(tdp / "missing_hf")}).encode("utf-8"), |
| 734 | headers={"Content-Type": "application/json"}, |
| 735 | method="POST", |
| 736 | ) |
| 737 | with self.assertRaises(urllib.error.HTTPError) as ctx: |
| 738 | urllib.request.urlopen(req_bad, timeout=10.0) |
| 739 | try: |
| 740 | self.assertEqual(ctx.exception.code, 400) |
| 741 | h_err = json.loads(ctx.exception.read().decode("utf-8")) |
| 742 | self.assertFalse(h_err["ok"]) |
| 743 | self.assertTrue(h_err["error"]) |
| 744 | finally: |
| 745 | ctx.exception.close() |
| 746 | finally: |
| 747 | srv.shutdown() |
| 748 | srv.server_close() |
| 749 | th.join(timeout=3.0) |
| 750 | |
| 751 | |
| 752 | if __name__ == "__main__": |
| 753 | unittest.main() |