Files
leleka/scripts/smoke-mtp-pack.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 97c33d8b2c Offline differentials: port the Strata 0.1.50 chat-template empty-turn filter, GGUF types 143-146, native PLE key types; fix two stale smokes
chat template (prompt bytes): ChatTemplate.render (#843) drops completed empty assistant turns
(no text after strip, no picture, no tool calls; the final message is kept; STRATA_KEEP_EMPTY_TURNS=1
keeps them) before the template runs. prompt.rs now does the same in Renderer::render and in the typed
render_with_images path. diff_chat_template: 136/3000 -> 0 (also 2 x 12000). chat_template_oracle.json
regenerated from the Original; one responses.rs test asserted the old behaviour.

gguf: block_geometry knows the APR trellis types 143-146 (PTQ1_0, TQ2_T, TQK6, TQK7); gguf_headers.json
regenerated. diff_gguf_header: 188/400 -> 0.

native pack: NATIVE_PLE_KEY gained IQ3_XXS/IQ4_XS (#381); NVFP4 expert tails and prism.hadamard experts
are refused (not ported, the runtime reads neither). diff_native_pack f16_nan uses a quiet NaN (numpy's
widening of a signaling NaN differs between builds). The live differential still needs one run on Linux.

smoke-mtp-pack.py reads the Q8_0 names from required[]/wq(); Dockerfile.systemd-smoke drops its apt
version pins. docs/ci-audit.md findings 14, 15, 16, 18 updated in place.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 03:39:53 +01:00

182 lines
10 KiB
Python

#!/usr/bin/env python3
"""Pinned MTP acquisition and structural preflight; synthetic CPU worker only."""
import copy
import hashlib
import http.client
import http.server
import importlib.util
import json
import os
from pathlib import Path
import re
import shutil
import socket
import subprocess
import struct
import sys
import tempfile
import threading
import time
REPO = Path(__file__).resolve().parents[1]
def main():
binary = str(Path(sys.argv[1]).resolve())
spec = importlib.util.spec_from_file_location('native_pack_fixture', Path(__file__).with_name('smoke-native-pack.py'))
fixture = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fixture)
with tempfile.TemporaryDirectory(prefix='strata-mtp-bootstrap-') as tmp:
root = Path(tmp).resolve()
source = root / 'http'; source.mkdir()
# Independent engine-consumer names, rather than the validator's own table.
consumer = (REPO / 'engine/strata/src/core/mtp.cpp').read_text()
# Engine 0.1.50 reads the Q8_0 weights through `wq("name", type)` (Q8_0, or Q4_0 under --mtp-q4) after checking them
# against the `required[]` list; the f32 and bf16 ones still go through `f32("name")` / `bf16("name")`.
required = re.search(r'const char\* required\[\] = \{(.*?)\};', consumer, re.S).group(1)
q8_names = set(re.findall(r'\bwq\("([^" ]+)"', consumer)) | set(re.findall(r'"([^"]+)"', required))
assert len(q8_names) == 9, q8_names # the drafter's nine Q8_0 projections; another count means mtp.cpp changed again
names = sorted(set(re.findall(r'\b(q8|bf16|f32)\("([^" ]+)"\)', consumer)) | {('q8', name) for name in q8_names})
records = json.loads((REPO / 'engine/strata/bench/results/2026-09-30-community-rtx-5090/mtp-manifest.json').read_text())
shapes = {t['name'].removeprefix('mtp.').removeprefix('layers.0.'): t['shape'] for t in records}
names += [('q8', 'self_attn.indexer.index_qk_proj.weight'), ('f32', 'self_attn.indexer.k_layernorm.weight'), ('f32', 'self_attn.indexer.q_layernorm.weight')]
offset = 0; lines = []
for kind, name in names:
kind = 'q8_0' if kind == 'q8' else kind
shape = shapes[name]
rows, cols = (1, shape[0]) if len(shape) == 1 else shape
offset = (offset + 255) // 256 * 256
size = rows * (cols // 32 * 34 if kind == 'q8_0' else cols * (4 if kind == 'f32' else 2))
lines.append(f'{name} {kind} {rows} {cols} {offset} {size}')
offset += size
with (source / 'dense.bin').open('wb') as f:
f.truncate(offset) # sparse synthetic values; geometry from independent pinned source
good_index = '\n'.join(lines) + '\n'
(source / 'dense.txt').write_text(good_index)
# Invalid pinned pack is deliberately tiny: verify no base-model fetch.
(source / 'experts.bin').write_bytes(b'invalid')
fixture.write_gguf(source / 'model.gguf', fixture.fixtures(), extra_fields=[
('qwen4exp.' + k, 4, struct.pack('<I', v)) for k, v in {
'block_count': 48, 'embedding_length': 2560, 'attention.head_count': 24,
'attention.head_count_kv': 2, 'expert_count': 256, 'expert_used_count': 10}.items()])
requests = []
class Source(http.server.BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_GET(self):
requests.append(self.path)
path = source / self.path.lstrip('/')
self.send_response(200)
self.send_header('Content-Length', str(path.stat().st_size))
self.end_headers()
with path.open('rb') as data:
shutil.copyfileobj(data, self.wfile, 1024 * 1024)
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Source)
thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()
def manifest(path, files):
records = []
for name in files:
with (source / name).open('rb') as f:
digest = hashlib.file_digest(f, 'sha256').hexdigest()
records.append({'name': name, 'size': (source / name).stat().st_size,
'sha256': digest, 'url': f'http://127.0.0.1:{server.server_port}/{name}'})
path.write_text(json.dumps({'schema_version': 1, 'files': records}))
model_manifest = root / 'model.json'; manifest(model_manifest, ['model.gguf'])
mtp_manifest = root / 'mtp.json'; manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin'])
marker = root / 'worker-started'
worker = root / 'worker.sh'
worker.write_text('''#!/bin/sh
set -eu
[ "$1" = --serve ]
[ "$3" = --mtp ]; [ -f "$4/experts.bin" ]
[ "$5" = --pack ]; [ -f "$6/receipt.json" ]
[ "$7" = --native ]; [ -f "$8" ]
printf '%s\\n%s\\n%s\\n' "$4" "$6" "$8" > "$2"
printf 'READY 256 stop\\n'
while IFS= read -r line; do case "$line" in QUIT) exit 0 ;; esac; done
''')
worker.chmod(0o700)
with socket.socket() as probe:
probe.bind(('127.0.0.1', 0)); port = probe.getsockname()[1]
mtp = root / 'mtp-v1'
config = {'bind': f'127.0.0.1:{port}', 'mtp_pack': str(mtp),
'assets': [{'manifest': str(mtp_manifest), 'directory': str(mtp)}],
'native_model': {'manifest': str(model_manifest), 'source_dir': str(root / 'base'), 'output': str(root / 'pack'), 'runtime_profile': 'qwen4exp-flash-next'},
'engine': {'executable': str(worker), 'args': [str(marker)], 'startup_timeout_s': 5, 'max_restarts': 0}}
path = root / 'config.json'
env = {'PATH': os.defpath}
def run(command='provision', ok=True):
path.write_text(json.dumps(config))
result = subprocess.run([binary, command, '--config', str(path)], env=env, capture_output=True, timeout=60)
assert (result.returncode == 0) == ok, (result.stdout, result.stderr)
return result
process = None
try:
assert json.loads(run('check-config').stdout)['mtp_pack'] == 'pinned_structural_check_pending'
assert not mtp.exists() and not requests
original = copy.deepcopy(config)
for args in [[str(marker), '--mtp', '/unused'], [str(marker), '--mtp=/unused']]:
config['engine']['args'] = args
run('serve', ok=False)
assert not requests and not marker.exists()
config = copy.deepcopy(original); config['assets'] = []
run('serve', ok=False); assert not requests
config = copy.deepcopy(original)
run('serve', ok=False)
assert requests == ['/dense.txt', '/dense.bin', '/experts.bin']
assert not (root / 'base').exists() and not marker.exists()
invalid = (mtp / 'experts.bin').read_bytes()
# Valid sparse shape/size fixture: no inference-quality assertion.
with (source / 'experts.bin').open('wb') as f:
f.truncate(512 * 3 * (2560 * 640 * 18 // 64))
manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin'])
mtp = root / 'mtp-v2'
config['mtp_pack'] = str(mtp); config['assets'][0]['directory'] = str(mtp)
# Correct bytes/ranges, but transpose the rectangular Q projection.
bad_index = good_index.replace('self_attn.q_proj.weight q8_0 12288 2560', 'self_attn.q_proj.weight q8_0 2560 12288')
assert bad_index != good_index
(source / 'dense.txt').write_text(bad_index)
manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin'])
assert b'geometry' in run(ok=False).stderr
assert not (root / 'base').exists() and not marker.exists()
assert '/model.gguf' not in requests
assert (mtp / 'dense.txt').read_text() == bad_index
# Publish the good profile as a new version; preserve both rejected versions.
(source / 'dense.txt').write_text(good_index)
manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin'])
mtp = root / 'mtp-v3'
config['mtp_pack'] = str(mtp); config['assets'][0]['directory'] = str(mtp)
assert json.loads(run().stdout)['mtp_pack_structurally_validated'] is True
assert requests[-4:] == ['/dense.txt', '/dense.bin', '/experts.bin', '/model.gguf']
assert (root / 'mtp-v1/experts.bin').read_bytes() == invalid and not marker.exists()
server.shutdown(); server.server_close(); thread.join()
count = len(requests)
run() # SHA verification and structural checks, offline reuse.
assert len(requests) == count
with tempfile.TemporaryFile() as log:
process = subprocess.Popen([binary, 'serve', '--config', str(path)], env=env, stdout=log, stderr=log)
deadline = time.monotonic() + 60
while True:
assert process.poll() is None and time.monotonic() < deadline
try:
c = http.client.HTTPConnection('127.0.0.1', port, timeout=1)
c.request('GET', '/ready'); response = c.getresponse(); response.read(); c.close()
if response.status == 200: break
except OSError:
pass
time.sleep(.03)
assert marker.read_text().splitlines() == [str(mtp), str(root / 'pack'), str(root / 'base/model.gguf')]
process.terminate(); assert process.wait(timeout=8) == 0
finally:
if process and process.poll() is None:
process.kill(); process.wait(timeout=5)
if thread.is_alive():
server.shutdown(); server.server_close(); thread.join()
print('MTP bootstrap passed: pinned HTTP, invalid pack before base fetch/worker, exact args, offline reuse and previous version preserved; independent pinned geometry and byte-consistent transpose rejection, synthetic values only, no GPU/model quality qualification')
if __name__ == '__main__':
main()