Files
leleka/scripts/offline/diff_native_pack.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 0d073e08aa feat(native-pack): match iq_pack.py conversions, add --compat-bf16/--base/--experts-bin and the exhaustive differential
- ple_conv1d inexact F32->F16 is accepted and recorded exact=false, as the oracle does
- conversions.json now carries method/exact/max_abs_err/source_shards like iq_pack.py
- opt-in --compat-bf16 (dequantize + RNE to BF16/F16/F32), --base (index_from_base, extra.bin),
  --experts-bin (+ experts.bin.src.json); receipts list the optional files present
- scripts/offline/diff_native_pack.py: 2700+ cases against the unmodified tools/iq_pack.py
- unit tests: real golden expert tables, numpy/gguf-py F16/BF16 rounding vectors
- fix three pre-existing clippy lints in leleka-model-format

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 15:20:15 +02:00

510 lines
26 KiB
Python

#!/usr/bin/env python3
"""Exhaustive native-pack differential: `strata-next model prepare-native-pack` vs the UNMODIFIED tools/iq_pack.py.
Every FORM tensor name (bare and under `blk.N.`) x every source type/value class x {default, --compat-bf16}, plus
shard topologies (1/2/4 shards, layers and roles split anywhere, multi-layer) and malformed inputs. For each case
both sides must make the same accept/reject decision and, when they accept, write byte-identical dense.bin, equal
index.txt rows, an equal native_experts.txt, equal conversions.json fields and an equal compat-bf16.json.
STRATA_GGUF_PY=<pinned llama.cpp>/gguf-py python scripts/offline/diff_native_pack.py <strata-next> [--quick]
Needs numpy and the pinned gguf-py (quantized sources). Offline, CPU only, synthetic data.
"""
import contextlib
import re
import zlib
import hashlib
import io
import json
import os
import shutil
import struct
import subprocess
import sys
import tempfile
from pathlib import Path
import numpy as np
REPO = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO / 'engine/strata/tools'))
sys.path.insert(0, str(Path(__file__).resolve().parent))
import iq_pack # noqa: E402 (the oracle, unchanged)
from ggufgen import write_gguf, string # noqa: E402
H, E = 256, 2 # hidden size / experts of the synthetic model
GGML = {'F32': 0, 'F16': 1, 'Q8_0': 8, 'Q4_K': 12, 'Q5_K': 13, 'Q6_K': 14, 'IQ3_XXS': 18, 'IQ4_NL': 20,
'IQ3_S': 21, 'IQ2_S': 22, 'IQ4_XS': 23, 'BF16': 30, 'Q2_0': 42}
BLOCK = {'Q8_0': (32, 34), 'Q4_K': (256, 144), 'Q5_K': (256, 176), 'Q6_K': (256, 210), 'IQ3_XXS': (256, 98),
'IQ4_NL': (32, 18), 'IQ3_S': (256, 110), 'IQ2_S': (256, 82), 'IQ4_XS': (256, 136), 'Q2_0': (64, 18)}
SCALE_AT = {'Q6_K': 208} # super-block scale `d` position (f16); the others start with it
FORM_NAMES = list(iq_pack.FORM)
def tokenizer_meta():
out = [('tokenizer.ggml.model', 'str', 'gpt2'), ('tokenizer.ggml.pre', 'str', 'qwen35'),
('tokenizer.chat_template', 'str', '{{ messages }}'),
('tokenizer.ggml.tokens', ('array', 'str'), ['a', 'b', 'ab', '<|im_end|>']),
('tokenizer.ggml.merges', ('array', 'str'), ['a b']),
('tokenizer.ggml.token_type', ('array', 'u32'), [1, 1, 1, 3]),
('tokenizer.ggml.eos_token_id', 'u32', 3)]
return out
def quant_bytes(rng, kind, n_elements, bad_scale=None):
elems, size = BLOCK[kind]
n = n_elements // elems
raw = rng.integers(0, 256, size=(n, size), dtype=np.uint8)
d = np.float16(rng.uniform(0.001, 0.05)) if bad_scale is None else np.float16(bad_scale)
at = SCALE_AT.get(kind, 0)
for b in range(n):
raw[b, at:at + 2] = np.frombuffer(np.float16(rng.uniform(0.001, 0.05) if bad_scale is None else d).tobytes(), np.uint8)
if kind in ('Q4_K', 'Q5_K'): # dmin follows d
for b in range(n):
raw[b, 2:4] = np.frombuffer(np.float16(rng.uniform(0.001, 0.05)).tobytes(), np.uint8)
return raw.tobytes()
def value_class(rng, cls, n):
"""(ggml type name, raw bytes) for a source class."""
f32 = lambda a: ('F32', np.asarray(a, np.float32).tobytes())
if cls == 'f32_bf16x':
a = rng.normal(size=n).astype(np.float32)
return f32((a.view(np.uint32) & 0xFFFF0000).view(np.float32))
if cls == 'f32_bf16x_inf':
a = (rng.normal(size=n).astype(np.float32).view(np.uint32) & 0xFFFF0000).view(np.float32).copy()
a[3] = np.inf
return f32(a)
if cls == 'f32_bf16x_nan':
a = (rng.normal(size=n).astype(np.float32).view(np.uint32) & 0xFFFF0000).view(np.float32).copy()
a[5] = np.uint32(0x7FC00000).view(np.float32)
return f32(a)
if cls == 'f32_random':
return f32(rng.normal(size=n))
if cls == 'f32_one_off': # one value off BF16 among exact ones
a = (rng.normal(size=n).astype(np.float32).view(np.uint32) & 0xFFFF0000).view(np.float32).copy()
a[7] = np.float32(1.00001)
return f32(a)
if cls == 'f32_halfway': # BF16 ties: even and odd mantissas, plus negatives
base = np.array([0x3F800000, 0x3F810000, 0x3F808000, 0x3F818000, 0xBF808000, 0xBF818000, 0x00008000,
0x7F7F8000, 0x00018000, 0x80008000], np.uint32)
a = np.resize(base, n).view(np.float32)
return f32(a)
if cls == 'f32_f16x': # exactly representable in F16
return f32(rng.normal(size=n).astype(np.float16).astype(np.float32))
if cls == 'f32_f16edge': # F16 subnormals, ties, max, overflow-rounding
base = np.array([0x33000000, 0x33800000, 0x34000000, 0x387FC000, 0x477FE000, 0x477FF000, 0x477FEFFF,
0xB8000000, 0x38000000, 0x33000001, 0x00000001, 0x80000000, 0x477FF001], np.uint32)
return f32(np.resize(base, n).view(np.float32))
if cls == 'f32_big':
a = rng.normal(size=n).astype(np.float32)
a[2] = 1e10
return f32(a)
if cls == 'f32_inf':
a = rng.normal(size=n).astype(np.float32)
a[1] = -np.inf
return f32(a)
if cls == 'f32_nan':
a = rng.normal(size=n).astype(np.float32)
a[4] = np.nan
return f32(a)
if cls in ('f16', 'f16_edge', 'f16_inf', 'f16_nan'):
a = rng.normal(size=n).astype(np.float16)
bits = a.view(np.uint16).copy()
if cls == 'f16_edge':
bits[:6] = [0x0001, 0x0400, 0x7BFF, 0x8001, 0x3C00, 0x8000]
if cls == 'f16_inf':
bits[2] = 0x7C00
if cls == 'f16_nan':
bits[2], bits[6] = 0x7E00, 0x7D55
return ('F16', bits.tobytes())
if cls in ('bf16', 'bf16_inf', 'bf16_nan', 'bf16_edge'):
a = (rng.normal(size=n).astype(np.float32).view(np.uint32) >> 16).astype(np.uint16)
if cls == 'bf16_inf':
a[2] = 0x7F80
if cls == 'bf16_nan':
a[2], a[6] = 0x7FC0, 0x7FA1
if cls == 'bf16_edge':
a[:4] = [0x0001, 0x0080, 0x7F7F, 0x8001]
return ('BF16', a.tobytes())
if cls == 'q:Q8_0_inf':
return ('Q8_0', quant_bytes(rng, 'Q8_0', n, bad_scale=np.inf))
if cls.startswith('q:'):
kind = cls[2:]
return (kind, quant_bytes(rng, kind, n))
raise KeyError(cls)
FLOAT_CLASSES = ['f32_bf16x', 'f32_bf16x_inf', 'f32_bf16x_nan', 'f32_random', 'f32_one_off', 'f32_halfway',
'f32_f16x', 'f32_f16edge', 'f32_big', 'f32_inf', 'f32_nan', 'f16', 'f16_edge', 'f16_inf',
'f16_nan', 'bf16', 'bf16_inf', 'bf16_nan', 'bf16_edge']
QUANT_CLASSES = ['q:' + k for k in BLOCK] + ['q:Q8_0_inf']
def base_tensors(rng):
"""The tensors every pack needs: layer-0 router and experts, an unlisted float, token_embd, the PLE table."""
zeros = lambda kind, nel: quant_bytes(rng, kind, nel)
return [
('blk.0.ffn_gate_inp.weight', [H, E], 0, np.full(H * E, 1.5, np.float32).tobytes()),
('blk.0.attn_q_norm.weight', [H], 30, np.full(H, 0x3fc0, np.uint16).tobytes()),
('unlisted_float.weight', [3], 1, np.arange(1, 4, dtype=np.float16).tobytes()),
('token_embd.weight', [H, 2], 21, zeros('IQ3_S', H * 2)),
('blk.1.ple_key.weight', [H, 2], 8, zeros('Q8_0', H * 2)),
('per_layer_token_embd.weight', [H, 2], 8, zeros('Q8_0', H * 2)),
*expert_tensors(rng, 0)]
def expert_tensors(rng, layer, gate_kind='IQ3_S', down_kind='IQ3_S'):
return [(f'blk.{layer}.ffn_gate_exps.weight', [H, H, E], GGML[gate_kind], quant_bytes(rng, gate_kind, H * H * E)),
(f'blk.{layer}.ffn_up_exps.weight', [H, H, E], GGML[gate_kind], quant_bytes(rng, gate_kind, H * H * E)),
(f'blk.{layer}.ffn_down_exps.weight', [H, H, E], GGML[down_kind], quant_bytes(rng, down_kind, H * H * E))]
def write_model(root, stem, shards, architecture='qwen4exp', total=None, split_override=None):
"""shards: list of tensor lists. Returns the shard paths (shard 1 first)."""
n = len(shards)
total = sum(len(s) for s in shards) if total is None else total
paths = [root / (f'{stem}-{i + 1:05}-of-{n:05}.gguf' if n > 1 else f'{stem}.gguf') for i in range(n)]
for i, (path, tensors) in enumerate(zip(paths, shards)):
meta = []
if i == 0:
if architecture:
meta.append(('general.architecture', 'str', architecture))
meta += tokenizer_meta()
if n > 1:
no, count, tt = (split_override or {}).get(i, (i, n, total))
meta += [('split.no', 'u16', no), ('split.count', 'u16', count), ('split.tensors.count', 'i32', tt)]
write_gguf(path, tensors, meta)
return paths
class Harness:
def __init__(self, binary):
self.binary = str(Path(binary).resolve())
self.root = Path(tempfile.mkdtemp(prefix='strata-pack-matrix-'))
self.count = 0
self.accepted = 0
self.rejected = 0
self.failures = []
self.unsupported = 0
self.known_stricter = 0
def close(self):
shutil.rmtree(self.root, ignore_errors=True)
def oracle(self, paths, compat):
out = self.root / 'oracle'
shutil.rmtree(out, ignore_errors=True)
out.mkdir()
with contextlib.redirect_stdout(io.StringIO()):
try:
model = iq_pack.Model(paths[0])
table = iq_pack.expert_layout(model, paths[0])
if isinstance(table, str):
return None
if iq_pack.index_standalone(paths[0], out, model, compat) != 0:
return None
except NotImplementedError:
return 'unsupported' # gguf-py cannot dequantize this type (Q2_0): nothing to compare against
except Exception: # noqa: BLE001 (a KeyError in the oracle is a refusal too)
return None
(out / 'native_experts.txt').write_text(table[1])
return out
def rust(self, paths, compat, extra=()):
out = self.root / 'rust'
shutil.rmtree(out, ignore_errors=True)
manifest = {'schema_version': 1, 'files': [
{'name': p.name, 'url': 'https://example.invalid/' + p.name, 'size': p.stat().st_size,
'sha256': hashlib.sha256(p.read_bytes()).hexdigest()} for p in reversed(paths)]}
mpath = self.root / 'manifest.json'
mpath.write_text(json.dumps(manifest))
cmd = [self.binary, 'model', 'prepare-native-pack', str(mpath), '--source-dir', str(paths[0].parent),
'--output', str(out)] + (['--compat-bf16'] if compat else []) + list(extra)
r = subprocess.run(cmd, env={'PATH': os.defpath}, text=True, capture_output=True, timeout=60)
stage = list(self.root.glob('.rust.native-pack-*.tmp'))
assert not stage, 'unremoved failed stage'
if r.returncode != 0:
assert not out.exists(), 'failed run published output'
return None, r.stderr
return out, json.loads(r.stdout)
def check(self, label, paths, compat=False):
self.count += 1
want = self.oracle(paths, compat)
if want == 'unsupported':
self.unsupported += 1
return
got, info = self.rust(paths, compat)
if want is not None and got is None and \
any(r['max_abs_err'] == float('inf') for r in json.loads((want / 'conversions.json').read_text())['tensors']):
# KNOWN DIVERGENCE (deliberate): iq_pack.py writes an infinity that BF16 rounding overflowed into and
# records max_abs_err=inf; the Rust packer refuses it, as both refuse F16 overflow.
self.known_stricter += 1
return
if (want is None) != (got is None):
self.failures.append(f'{label} compat={compat}: oracle {"accepts" if want else "rejects"}, '
f'rust {"accepts" if got else "rejects: " + str(info).strip()[-160:]}')
return
if want is None:
self.rejected += 1
return
self.accepted += 1
problems = compare_packs(want, got, compat)
if problems:
self.failures.append(f'{label} compat={compat}: ' + '; '.join(problems))
def rows(path):
return [ln for ln in path.read_text().splitlines() if not ln.startswith('#')]
def compare_packs(want, got, compat, base=False):
bad = []
if (want / 'dense.bin').read_bytes() != (got / 'dense.bin').read_bytes():
bad.append('dense.bin differs')
if rows(want / 'index.txt') != rows(got / 'index.txt'):
bad.append('index rows differ')
if (want / 'index.txt').read_text().splitlines()[1:2] != (got / 'index.txt').read_text().splitlines()[1:2]:
bad.append('index pool/tensor header differs')
if (want / 'native_experts.txt').read_text() != (got / 'native_experts.txt').read_text():
bad.append('native_experts.txt differs')
if base: # iq_pack.py --base writes no conversions.json (the Rust pack needs one: empty list)
return bad
a = json.loads((want / 'conversions.json').read_text())
b = json.loads((got / 'conversions.json').read_text())
for key in ('schema', 'compat_bf16', 'source_shards'):
if a[key] != b[key]:
bad.append(f'conversions.{key} differs')
if a['tensors'] != b['tensors']:
first = next((x, y) for x, y in zip(a['tensors'] + [None], b['tensors'] + [None]) if x != y)
bad.append('conversions tensors differ: oracle %s vs rust %s' % first)
if compat:
c = json.loads((want / 'compat-bf16.json').read_text())
d = json.loads((got / 'compat-bf16.json').read_text())
if (c['rounding'], c['tensors']) != (d['rounding'], d['tensors']):
bad.append('compat-bf16.json differs')
elif (got / 'compat-bf16.json').exists():
bad.append('unexpected compat-bf16.json')
return bad
def single_tensor_cases(h, rng, quick):
names = []
for key in FORM_NAMES:
names += [key, 'blk.1.' + key]
names += ['blk.2.ple_key.weight']
classes = FLOAT_CLASSES + QUANT_CLASSES
quantized_names = {'ffn_gate_inp.weight', 'ple_conv1d.weight', 'attn_q_norm.weight', 'ple_key.weight',
'ssm_a', 'ple_value.weight', 'hc_attn_down.weight'}
for name in names:
for cls in classes:
seed = zlib.crc32(f'{name}/{cls}'.encode())
if quick and seed % 5:
continue
if cls.startswith('q:') and re.sub(r'^blk\.\d+\.', '', name) not in quantized_names:
continue
type_name, raw = value_class(np.random.default_rng(seed), cls, H * 2)
tensors = [t for t in base_tensors(rng) if t[0] != name]
tensors.append((name, [H, 2], GGML[type_name], raw))
paths = write_model(h.root, 'case', [tensors])
for compat in (False, True):
h.check(f'{name} <- {cls}', paths, compat)
def topology_cases(h, rng):
def layer_rows(layers, gate='IQ3_S', down='IQ3_S'):
out = []
for layer in range(layers):
out.append((f'blk.{layer}.ffn_gate_inp.weight', [H, E], 0, np.full(H * E, 1.5, np.float32).tobytes()))
out += expert_tensors(rng, layer, gate, down)
return out
common = [('token_embd.weight', [H, 2], 21, quant_bytes(rng, 'IQ3_S', H * 2)),
('unlisted.weight', [4], 0, np.arange(4, dtype=np.float32).tobytes())]
# single shard, several layers with mixed expert types
t = common + layer_rows(1) + layer_rows(3)[4:]
t = [x for x in t if not (x[0] == 'blk.0.ffn_gate_inp.weight' and sum(1 for y in t if y[0] == x[0]) > 1)]
seen, uniq = set(), []
for x in t:
if x[0] not in seen:
seen.add(x[0])
uniq.append(x)
h.check('multi-layer single shard', write_model(h.root, 'multi', [uniq]))
mixed = common + layer_rows(1, 'IQ3_S', 'IQ4_NL') + [
x for x in layer_rows(2, 'IQ2_S', 'Q2_0')[4:]]
h.check('mixed expert types', write_model(h.root, 'mixed', [mixed]))
# split topologies over 3 layers
allt = common + layer_rows(3)
by_name = {x[0]: x for x in allt}
layers = [[by_name[f'blk.{l}.ffn_gate_inp.weight'], by_name[f'blk.{l}.ffn_gate_exps.weight'],
by_name[f'blk.{l}.ffn_up_exps.weight'], by_name[f'blk.{l}.ffn_down_exps.weight']] for l in range(3)]
flat = lambda *groups: [x for g in groups for x in g]
h.check('2 shards: layers 1-2 in shard 2', write_model(h.root, 'two', [common + layers[0], flat(layers[1], layers[2])]))
h.check('2 shards: down roles in shard 2', write_model(h.root, 'twor', [
common + [x for l in layers for x in l[:3]], [l[3] for l in layers]]))
h.check('2 shards: layer split mid-layer', write_model(h.root, 'twom', [
common + layers[0] + layers[1][:2], [layers[1][2], layers[1][3]] + layers[2][:]]))
h.check('2 shards: shard 1 holds no expert at all', write_model(h.root, 'twoe', [
common + [layers[0][0], layers[1][0], layers[2][0]],
flat(*[l[1:] for l in layers])]))
h.check('4 shards: one layer per shard + dense first', write_model(h.root, 'four', [
common + [layers[0][0]], layers[0][1:] + [layers[1][0]], layers[1][1:] + [layers[2][0]], layers[2][1:]]))
h.check('4 shards: roles scattered', write_model(h.root, 'fours', [
common + [layers[0][0], layers[1][0], layers[2][0]],
[layers[0][1], layers[1][3]], [layers[0][2], layers[2][1]], [layers[0][3], layers[1][2], layers[2][2],
layers[2][3]]]))
h.check('pruned experts (router 2 cols everywhere)', write_model(h.root, 'pr', [common + layers[0]]))
# malformed
h.check('reject: duplicate tensor in two shards', write_model(h.root, 'dup', [
common + layers[0], [layers[0][3]]], total=len(common + layers[0]) + 1))
h.check('reject: shard 2 declares a foreign split', write_model(h.root, 'foreign', [
common + layers[0][:2], layers[0][2:]], split_override={1: (1, 2, 999)}))
h.check('reject: shard 2 declares split.no 0', write_model(h.root, 'norepeat', [
common + layers[0][:2], layers[0][2:]], split_override={1: (0, 2, len(common + layers[0]))}))
h.check('reject: missing expert role', write_model(h.root, 'missing', [common + layers[0][:3]]))
h.check('reject: missing router', write_model(h.root, 'norouter', [common + layers[0][1:]]))
h.check('reject: router disagrees on expert count', write_model(h.root, 'rdis', [
common + layers[0] + [('blk.1.ffn_gate_inp.weight', [H, E + 1], 0, np.zeros(H * (E + 1), np.float32).tobytes())]
+ layers[1][1:]]))
h.check('reject: gate/up types differ', write_model(h.root, 'gudiff', [
common + [layers[0][0], expert_tensors(rng, 0, 'IQ3_S')[0], expert_tensors(rng, 0, 'IQ2_S')[1],
expert_tensors(rng, 0)[2]]]))
h.check('reject: 3-D dense tensor', write_model(h.root, 'dense3', [
common + layers[0] + [('odd.weight', [4, 2, 2], 0, np.zeros(16, np.float32).tobytes())]]))
h.check('reject: expert has wrong expert count', write_model(h.root, 'badE', [
common + [layers[0][0]] + [(n, [H, H, E + 1], k, quant_bytes(rng, 'IQ3_S', H * H * (E + 1)))
for n, _, k, _ in layers[0][1:]]]))
# truncated file: cut the last tensor
paths = write_model(h.root, 'trunc', [common + layers[0]])
data = paths[0].read_bytes()
paths[0].write_bytes(data[:-100])
h.check('reject: truncated shard', paths)
def full_pack_cases(h, rng):
"""Whole-CLI comparison: tools/iq_pack.py as a subprocess (tokenizer, experts.bin, --base) vs strata-next."""
py = sys.executable
tool = str(REPO / 'engine/strata/tools/iq_pack.py')
def cli(label, paths, flags, base_flags=(), rust_flags=None):
h.count += 1
want = h.root / 'cli-oracle'
shutil.rmtree(want, ignore_errors=True)
r = subprocess.run([py, tool, '--gguf', str(paths[0]), '--out', str(want), *flags], text=True,
capture_output=True, env={**os.environ, 'PYTHONWARNINGS': 'ignore'})
got, info = h.rust(paths, False, rust_flags if rust_flags is not None else flags)
if (r.returncode == 0) != (got is not None):
h.failures.append(f'{label}: oracle rc={r.returncode} ({r.stdout.strip()[-100:]}), rust '
f'{"accepts" if got else "rejects: " + str(info)[-200:]}')
return None
if got is None:
h.rejected += 1
return None
h.accepted += 1
problems = compare_packs(want, got, '--compat-bf16' in flags, '--base' in flags)
for name in ('experts.bin', 'extra.bin'):
if (want / name).exists() != (got / name).exists():
problems.append(f'{name} presence differs')
elif (want / name).exists() and (want / name).read_bytes() != (got / name).read_bytes():
problems.append(f'{name} differs')
if (want / 'experts.bin.src.json').exists():
if json.loads((want / 'experts.bin.src.json').read_text()) != \
json.loads((got / 'experts.bin.src.json').read_text()):
problems.append('experts.bin.src.json differs')
for name in ('vocab.json', 'token_type.json'):
if json.loads((want / 'tokenizer' / name).read_text()) != json.loads((got / 'tokenizer' / name).read_text()):
problems.append(f'tokenizer/{name} differs')
for name in ('merges.txt', 'chat_template.jinja'):
if (want / 'tokenizer' / name).read_bytes() != (got / 'tokenizer' / name).read_bytes():
problems.append(f'tokenizer/{name} differs')
a = json.loads((want / 'tokenizer/tokenizer.json').read_text())
b = json.loads((got / 'tokenizer/tokenizer.json').read_text())
for k in a:
if k in b and a[k] != b[k]:
problems.append(f'tokenizer.json {k}: {a[k]!r} vs {b[k]!r}')
if problems:
h.failures.append(f'{label}: ' + '; '.join(problems))
return got
def layer(i, gate='IQ3_S', down='IQ3_S'):
return [(f'blk.{i}.ffn_gate_inp.weight', [H, E], 0, np.full(H * E, 1.5, np.float32).tobytes()),
*expert_tensors(rng, i, gate, down)]
dense = [('token_embd.weight', [H, 2], 21, quant_bytes(rng, 'IQ3_S', H * 2)),
('blk.0.attn_q_norm.weight', [H], 30, np.full(H, 0x3fc0, np.uint16).tobytes()),
('blk.1.ple_conv1d.weight', [2], 0, np.array([1.00001, -2.0], np.float32).tobytes()),
('blk.1.ple_key.weight', [H, 2], 8, quant_bytes(rng, 'Q8_0', H * 2)),
('blk.3.hc_attn_down.weight', [H, 2], 0,
(rng.normal(size=H * 2).astype(np.float32).view(np.uint32) & 0xFFFF0000).view(np.float32).tobytes()),
('blk.0.ssm_a', [4], 1, np.arange(1, 5, dtype=np.float16).tobytes()),
('per_layer_token_embd.weight', [H, 2], 8, quant_bytes(rng, 'Q8_0', H * 2))]
model = dense + layer(0) + layer(1, 'IQ4_NL', 'Q2_0') + layer(2)
one = write_model(h.root, 'cli1', [model])
cli('cli: default single', one, [])
q8 = [t if t[0] != 'blk.3.hc_attn_down.weight' else (t[0], t[1], 8, quant_bytes(rng, 'Q8_0', H * 2))
for t in model]
q8p = write_model(h.root, 'cliq8', [q8])
cli('cli: Q8_0 projection without --compat-bf16 (reject)', q8p, [])
cli('cli: --compat-bf16', q8p, ['--compat-bf16'])
cli('cli: --experts-bin', one, ['--experts-bin'])
cli('cli: --compat-bf16 --experts-bin', q8p, ['--compat-bf16', '--experts-bin'])
by = {t[0]: t for t in model}
lay = lambda i: [by[f'blk.{i}.ffn_gate_inp.weight'], by[f'blk.{i}.ffn_gate_exps.weight'],
by[f'blk.{i}.ffn_up_exps.weight'], by[f'blk.{i}.ffn_down_exps.weight']]
two = write_model(h.root, 'cli2', [dense[:-1] + lay(0) + [lay(1)[0]] + lay(1)[1:2],
lay(1)[2:] + lay(2) + dense[-1:]])
cli('cli: 2 shards, layer split inside layer 1, --experts-bin', two, ['--experts-bin'])
cli('cli: 2 shards, --compat-bf16', two, ['--compat-bf16'])
# --base: a canonical pack of a model whose PLE key is quantized; the new model has it as BF16
model = q8
base_model = [t if t[0] != 'blk.1.ple_key.weight' else ('blk.1.ple_key.weight', [H, 2], GGML['Q2_0'],
quant_bytes(rng, 'Q2_0', H * 2)) for t in model]
for variant in ('plain', 'ple-bf16', 'q8-both'):
new_model = [t for t in base_model]
if variant == 'ple-bf16':
new_model = [t if t[0] != 'blk.1.ple_key.weight' else ('blk.1.ple_key.weight', [H, 2], 30,
np.full(H * 2, 0x3f80, np.uint16).tobytes())
for t in base_model]
if variant == 'q8-both':
base_model2 = base_model
base_paths = write_model(h.root, f'base-{variant}', [base_model])
base_out = h.root / f'base-pack-{variant}'
shutil.rmtree(base_out, ignore_errors=True)
r = subprocess.run([py, tool, '--gguf', str(base_paths[0]), '--out', str(base_out), '--compat-bf16'], capture_output=True,
text=True, env={**os.environ, 'PYTHONWARNINGS': 'ignore'})
assert r.returncode == 0, r.stdout + r.stderr
(base_out / 'manifest.json').write_text(json.dumps({'source': {'shard1': str(base_paths[0].absolute())}}))
new_paths = write_model(h.root, f'new-{variant}', [new_model])
flags = ['--base', str(base_out)]
cli(f'cli: --base ({variant})', new_paths, flags)
# --base refused: a float tensor differs from the base; missing tensor; sharded; compat together
changed = [t if t[0] != 'blk.0.ssm_a' else ('blk.0.ssm_a', [4], 1, np.arange(2, 6, dtype=np.float16).tobytes())
for t in base_model]
cli('cli: --base reject (float tensor differs)', write_model(h.root, 'new-diff', [changed]), ['--base', str(base_out)])
cli('cli: --base reject (tensor missing)', write_model(h.root, 'new-miss', [[t for t in base_model if t[0] != 'blk.0.ssm_a']]),
['--base', str(base_out)])
def main():
quick = '--quick' in sys.argv
args = [a for a in sys.argv[1:] if not a.startswith('--')]
h = Harness(args[0])
rng = np.random.default_rng(1234)
try:
topology_cases(h, rng)
full_pack_cases(h, rng)
single_tensor_cases(h, rng, quick)
finally:
h.close()
for f in h.failures[:60]:
print('FAIL', f)
print(json.dumps({'cases': h.count, 'accepted': h.accepted, 'rejected': h.rejected,
'oracle_cannot_dequantize': h.unsupported, 'known_stricter_bf16_overflow': h.known_stricter, 'failures': len(h.failures), 'oracle': 'tools/iq_pack.py (unmodified)'}))
return 1 if h.failures else 0
if __name__ == '__main__':
raise SystemExit(main())