Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
167 lines
8.6 KiB
Python
167 lines
8.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Independent pinned Python pack oracle versus the native Rust CLI, CPU only."""
|
|
import contextlib
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
REPO = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(REPO / 'engine/strata/tools'))
|
|
import iq_pack # Existing oracle, unchanged; numpy is test-only.
|
|
|
|
|
|
def string(s):
|
|
b = s.encode()
|
|
return struct.pack('<Q', len(b)) + b
|
|
|
|
|
|
def write_gguf(path, tensors, split=None, architecture='qwen4exp', tokenizer=True, extra_fields=()):
|
|
fields = list(extra_fields)
|
|
if architecture:
|
|
fields.append(('general.architecture', 8, string(architecture)))
|
|
if split is not None:
|
|
fields += [('split.no', 2, struct.pack('<H', split[0])),
|
|
('split.count', 2, struct.pack('<H', split[1])),
|
|
('split.tensors.count', 5, struct.pack('<i', split[2]))]
|
|
if tokenizer:
|
|
fields += [(k, 8, string(v)) for k, v in [
|
|
('tokenizer.ggml.model', 'gpt2'), ('tokenizer.ggml.pre', 'qwen35'),
|
|
('tokenizer.chat_template', '{{ messages }}')]]
|
|
for k, vals in [('tokenizer.ggml.tokens', ['a', 'b', 'ab', '<|im_end|>']),
|
|
('tokenizer.ggml.merges', ['a b'])]:
|
|
fields.append((k, 9, struct.pack('<IQ', 8, len(vals)) + b''.join(map(string, vals))))
|
|
fields.append(('tokenizer.ggml.token_type', 9, struct.pack('<IQ4I', 4, 4, 1, 1, 1, 3)))
|
|
fields.append(('tokenizer.ggml.eos_token_id', 4, struct.pack('<I', 3)))
|
|
header = b'GGUF' + struct.pack('<IQQ', 3, len(tensors), len(fields))
|
|
for k, kind, value in fields:
|
|
header += string(k) + struct.pack('<I', kind) + value
|
|
body = b''
|
|
for name, dims, kind, raw in tensors:
|
|
header += string(name) + struct.pack('<I', len(dims))
|
|
header += struct.pack('<' + 'Q' * len(dims), *dims) + struct.pack('<IQ', kind, len(body))
|
|
body += raw
|
|
body += bytes(-len(body) % 32)
|
|
header += bytes(-len(header) % 32)
|
|
path.write_bytes(header + body)
|
|
|
|
|
|
def fixtures():
|
|
# GGUF dimensions are fastest-first. Quantized expert bytes are opaque;
|
|
# both packers preserve them in GGUF, and only derive per-role offsets.
|
|
return [
|
|
('blk.0.ffn_gate_inp.weight', [256, 2], 0, struct.pack('<f', 1.5) * 512),
|
|
('blk.0.attn_q_norm.weight', [256], 30, struct.pack('<H', 0x3fc0) * 256),
|
|
('blk.0.attn_k_norm.weight', [256], 1, struct.pack('<e', -2.0) * 256),
|
|
('blk.1.ple_conv1d.weight', [2], 0, struct.pack('<2f', 1.5, -2.0)),
|
|
('unlisted_float.weight', [3], 1, struct.pack('<3e', 1, 2, 3)),
|
|
('token_embd.weight', [256, 2], 21, bytes(range(110)) * 2),
|
|
('blk.1.ple_key.weight', [256, 2], 8, bytes(range(34)) * 16),
|
|
('per_layer_token_embd.weight', [256, 2], 8, bytes(range(34)) * 16),
|
|
*[(f'blk.0.ffn_{r}_exps.weight', [256, 256, 2], 21, bytes(range(110)) * 512)
|
|
for r in ['gate', 'up', 'down']]]
|
|
|
|
|
|
def main():
|
|
binary = str(Path(sys.argv[1]).resolve())
|
|
count = 0
|
|
with tempfile.TemporaryDirectory(prefix='strata-native-pack-') as tmp:
|
|
root = Path(tmp).resolve()
|
|
manifest_path = root / 'manifest.json'
|
|
env = {'PATH': os.defpath}
|
|
|
|
def run(paths, output, ok=True):
|
|
nonlocal count
|
|
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)]}
|
|
manifest_path.write_text(json.dumps(manifest))
|
|
result = subprocess.run([binary, 'model', 'prepare-native-pack', str(manifest_path),
|
|
'--source-dir', str(root), '--output', str(output)],
|
|
env=env, text=True, capture_output=True, timeout=15)
|
|
assert (result.returncode == 0) == ok, result.stdout + result.stderr
|
|
assert not list(root.glob(f'.{output.name}.native-pack-*.tmp')), 'unremoved failed stage'
|
|
if ok:
|
|
report = json.loads(result.stdout)
|
|
assert report['prepared'] and not report['lossy_conversions'] and not report['gpu_validated']
|
|
count += 1
|
|
return result
|
|
|
|
for split in [False, True]:
|
|
tensors = fixtures()
|
|
paths = [root / 'single.gguf'] if not split else [root / f'split-{n:05}-of-00002.gguf' for n in [1, 2]]
|
|
if split:
|
|
write_gguf(paths[0], tensors[:-1], (0, 2, len(tensors)))
|
|
write_gguf(paths[1], tensors[-1:], (1, 2, len(tensors)), architecture=None, tokenizer=False)
|
|
else:
|
|
write_gguf(paths[0], tensors)
|
|
source_before = [p.read_bytes() for p in paths]
|
|
output = root / ('rust-split' if split else 'rust-single')
|
|
oracle = root / ('oracle-split' if split else 'oracle-single')
|
|
oracle.mkdir()
|
|
with contextlib.redirect_stdout(io.StringIO()):
|
|
model = iq_pack.Model(paths[0])
|
|
table = iq_pack.expert_layout(model, paths[0])
|
|
assert not isinstance(table, str), table
|
|
assert iq_pack.index_standalone(paths[0], oracle, model) == 0
|
|
run(paths, output)
|
|
assert (output / 'dense.bin').read_bytes() == (oracle / 'dense.bin').read_bytes()
|
|
assert (output / 'index.txt').read_text().splitlines()[1:] == (oracle / 'index.txt').read_text().splitlines()[1:]
|
|
assert (output / 'native_experts.txt').read_text() == table[1]
|
|
native_conv = json.loads((output / 'conversions.json').read_text())['tensors']
|
|
oracle_conv = json.loads((oracle / 'conversions.json').read_text())['tensors']
|
|
assert len(native_conv) == len(oracle_conv)
|
|
for a, b in zip(native_conv, oracle_conv):
|
|
assert all(a[k] == b[k] for k in ['name', 'shard', 'src_type', 'dst_type', 'exact', 'max_abs_err', 'source_sha256'])
|
|
assert json.loads((output / 'tokenizer/vocab.json').read_text()) == {'a': 0, 'b': 1, 'ab': 2, '<|im_end|>': 3}
|
|
assert (output / 'tokenizer/merges.txt').read_text() == 'a b'
|
|
assert [p.read_bytes() for p in paths] == source_before
|
|
before = (output / 'dense.bin').read_bytes()
|
|
run(paths, output, ok=False)
|
|
assert (output / 'dense.bin').read_bytes() == before
|
|
|
|
# Failed preparation must publish no output, even after partial dense writes.
|
|
source = root / 'failure.gguf'
|
|
cases = []
|
|
t = fixtures(); t[0] = (*t[0][:3], struct.pack('<f', 1.00001) * 512); cases.append(t)
|
|
t = fixtures(); t[3] = (*t[3][:3], struct.pack('<2f', 1.00001, -2)); cases.append(t)
|
|
t = fixtures(); t.pop(); cases.append(t) # missing expert role
|
|
t = fixtures(); t[-1] = (t[-1][0], [512, 128, 2], *t[-1][2:]); cases.append(t)
|
|
t = fixtures(); t[0] = (*t[0][:3], struct.pack('<f', float('inf')) * 512); cases.append(t)
|
|
for index, tensors in enumerate(cases):
|
|
write_gguf(source, tensors)
|
|
output = root / f'rejected-{index}'
|
|
run([source], output, ok=False)
|
|
assert not output.exists()
|
|
write_gguf(source, fixtures(), architecture='unsupported')
|
|
run([source], root / 'wrong-arch', ok=False)
|
|
write_gguf(source, fixtures(), (0, 2, len(fixtures())))
|
|
run([source], root / 'missing-shard', ok=False)
|
|
paths = [root / f'bad-{n:05}-of-00002.gguf' for n in [1, 2]]
|
|
write_gguf(paths[0], fixtures()[:-1], (0, 2, len(fixtures())))
|
|
write_gguf(paths[1], fixtures()[-1:], (1, 2, 999), architecture=None, tokenizer=False)
|
|
run(paths, root / 'bad-total', ok=False)
|
|
assert not (root / 'bad-total').exists()
|
|
# Full source SHA is checked before any pack can be published.
|
|
pins = json.loads(manifest_path.read_text())
|
|
pins['files'][0]['sha256'] = '0' * 64
|
|
manifest_path.write_text(json.dumps(pins))
|
|
result = subprocess.run([binary, 'model', 'prepare-native-pack', str(manifest_path),
|
|
'--source-dir', str(root), '--output', str(root / 'bad-sha')],
|
|
env=env, capture_output=True, text=True, timeout=15)
|
|
assert result.returncode != 0 and 'SHA-256' in result.stderr, result.stderr
|
|
assert not (root / 'bad-sha').exists()
|
|
count += 1
|
|
print(json.dumps({'status': 'passed', 'scenarios': count, 'oracle': 'pinned tools/iq_pack.py',
|
|
'dense_bytes_and_layout_tolerance': 0, 'real_model': False, 'gpu_used': False}))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|