187 lines
7.5 KiB
Python
187 lines
7.5 KiB
Python
#!/usr/bin/env python3
|
|
"""mtp_fetch differential: `leleka-api tools mtp-fetch` vs the unmodified tools/mtp_fetch.py, both against the same
|
|
local HTTP mirror of a fake checkpoint (the fixture pattern of tools/test_mtp_fetch.py, here a real socket).
|
|
|
|
Scenarios: honest fetch + verify; a corrupted install re-fetched; a resumed half tensor; `--only`; a mirror that
|
|
ignores Range (both must refuse and leave no tensor); inventory-only. After each, the output directories must
|
|
match file for file (inventory json/md, manifest, every tensor, verified.json modulo mtime).
|
|
|
|
python scripts/offline/diff_mtp_fetch.py <leleka-api>
|
|
"""
|
|
import hashlib
|
|
import http.server
|
|
import json
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
from pathlib import Path
|
|
from unittest import mock
|
|
|
|
REPO = Path(__file__).resolve().parents[2]
|
|
sys.path.insert(0, str(REPO / 'engine/strata/tools'))
|
|
import mtp_fetch as M # noqa: E402 (the oracle, unchanged)
|
|
|
|
|
|
def shard(tensors):
|
|
header, data = {}, b''
|
|
for name, blob in tensors:
|
|
header[name] = {'dtype': 'BF16', 'shape': [len(blob) // 2], 'data_offsets': [len(data), len(data) + len(blob)]}
|
|
data += blob
|
|
h = json.dumps(header).encode()
|
|
return struct.pack('<Q', len(h)) + h + data
|
|
|
|
|
|
A, B, X = bytes(range(64)), bytes(range(100, 164)) * 2, b'\x07' * 48
|
|
C = bytes(range(200, 256)) * 3
|
|
FILES = {'model-1.safetensors': shard([('model.x', X), ('mtp.a', A)]),
|
|
'model-2.safetensors': shard([('mtp.b', B), ('mtp.c', C)])}
|
|
INDEX = json.dumps({'weight_map': {'model.x': 'model-1.safetensors', 'mtp.a': 'model-1.safetensors',
|
|
'mtp.b': 'model-2.safetensors', 'mtp.c': 'model-2.safetensors'}}).encode()
|
|
HASHES = {n: hashlib.sha256(b).hexdigest() for n, b in (('mtp.a', A), ('mtp.b', B), ('mtp.c', C))}
|
|
STATE = {'ignore_range': False, 'cut': False}
|
|
|
|
|
|
class Handler(http.server.BaseHTTPRequestHandler):
|
|
protocol_version = 'HTTP/1.0'
|
|
|
|
def log_message(self, *args):
|
|
pass
|
|
|
|
def do_HEAD(self):
|
|
self.send_response(200)
|
|
self.end_headers()
|
|
|
|
def do_GET(self):
|
|
name = self.path.lstrip('/')
|
|
body = INDEX if name == 'model.safetensors.index.json' else FILES.get(name)
|
|
if body is None:
|
|
self.send_response(404)
|
|
self.end_headers()
|
|
return
|
|
rng = self.headers.get('Range')
|
|
if rng is None:
|
|
self.send_response(200)
|
|
self.send_header('Content-Length', str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
return
|
|
a, b = map(int, rng.split('=')[1].split('-'))
|
|
if STATE['ignore_range']:
|
|
sent = body[:b - a + 1] if STATE['cut'] else body
|
|
self.send_response(200)
|
|
self.send_header('Content-Length', str(len(sent)))
|
|
self.end_headers()
|
|
self.wfile.write(sent)
|
|
return
|
|
part = body[a:b + 1]
|
|
self.send_response(206)
|
|
self.send_header('Content-Range', 'bytes %d-%d/%d' % (a, b, len(body)))
|
|
self.send_header('Content-Length', str(len(part)))
|
|
self.end_headers()
|
|
self.wfile.write(part)
|
|
|
|
|
|
def python_run(url, cmd, out, only=None):
|
|
"""Run the oracle in-process against `url`; returns (exit code, bad list)."""
|
|
with mock.patch.object(M, 'REPO', url), mock.patch.object(M, 'PINNED', url), \
|
|
mock.patch.object(M, 'SHA256', HASHES), mock.patch.object(M.time, 'sleep', lambda s: None):
|
|
import contextlib
|
|
import io
|
|
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
|
try:
|
|
if cmd == 'fetch':
|
|
M.fetch(str(out), only)
|
|
elif cmd == 'inventory':
|
|
M.inventory(str(out))
|
|
else:
|
|
return 0, M.verify(str(out))
|
|
return 0, []
|
|
except SystemExit as e:
|
|
return (e.code if isinstance(e.code, int) else 1), []
|
|
except Exception: # noqa: BLE001
|
|
return 1, []
|
|
|
|
|
|
def rust_run(binary, url, cmd, out, hashes_file, only=None):
|
|
args = [binary, 'tools', 'mtp-fetch', cmd, '--out', str(out), '--repo', url, '--sha256-file', str(hashes_file)]
|
|
if only:
|
|
args += ['--only', only]
|
|
r = subprocess.run(args, capture_output=True, text=True)
|
|
bad = [l.split(': ', 1)[1] for l in r.stderr.splitlines() if l.startswith('MTP tensor missing or corrupt: ')]
|
|
return r.returncode, bad
|
|
|
|
|
|
def compare(py, rs, label, bad):
|
|
names = lambda root: sorted(str(p.relative_to(root)) for p in Path(root).rglob('*') if p.is_file())
|
|
if names(py) != names(rs):
|
|
bad.append(f'{label}: file sets differ {names(py)} vs {names(rs)}')
|
|
return
|
|
for name in names(py):
|
|
a, b = (Path(py) / name).read_bytes(), (Path(rs) / name).read_bytes()
|
|
if name.endswith('verified.json'):
|
|
strip = lambda raw: {k: [v[0], v[2]] for k, v in json.loads(raw).items()}
|
|
a, b = strip(a), strip(b)
|
|
if a != b:
|
|
bad.append(f'{label}: {name} differs')
|
|
|
|
|
|
def main():
|
|
binary = str(Path(sys.argv[1]).resolve())
|
|
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
url = f'http://127.0.0.1:{server.server_address[1]}/'
|
|
root = Path(tempfile.mkdtemp(prefix='strata-mtp-fetch-diff-'))
|
|
hashes_file = root / 'hashes.json'
|
|
hashes_file.write_text(json.dumps(HASHES))
|
|
bad, scenarios = [], 0
|
|
|
|
def both(label, cmd, py, rs, only=None):
|
|
nonlocal scenarios
|
|
scenarios += 1
|
|
pc, pbad = python_run(url, cmd, py, only)
|
|
rc, rbad = rust_run(binary, url, cmd, rs, hashes_file, only)
|
|
if cmd == 'verify': # the Python main() exits 3 (BAD) when verify() returns names
|
|
if pbad != rbad or rc != (3 if pbad else 0):
|
|
bad.append(f'{label}: python bad {pbad}, rust exit {rc} bad {rbad}')
|
|
elif (pc == 0) != (rc == 0):
|
|
bad.append(f'{label}: python exit {pc}, rust exit {rc}')
|
|
compare(py, rs, label, bad)
|
|
|
|
py, rs = root / 'py1', root / 'rs1'
|
|
both('fetch', 'fetch', py, rs)
|
|
both('verify', 'verify', py, rs)
|
|
for out in (py, rs): # a corrupted install, same size
|
|
(out / 'tensors/mtp.a.bin').write_bytes(bytes(len(A)))
|
|
both('verify finds the corruption', 'verify', py, rs)
|
|
both('refetch', 'fetch', py, rs)
|
|
both('verify after refetch', 'verify', py, rs)
|
|
py, rs = root / 'py2', root / 'rs2'
|
|
for out in (py, rs):
|
|
(out / 'tensors').mkdir(parents=True)
|
|
both('inventory', 'inventory', py, rs)
|
|
for out in (py, rs): # a half tensor to resume
|
|
(out / 'tensors/mtp.b.bin').write_bytes(B[:37])
|
|
both('resume', 'fetch', py, rs)
|
|
py, rs = root / 'py3', root / 'rs3'
|
|
both('--only', 'fetch', py, rs, only='mtp.c')
|
|
STATE.update(ignore_range=True, cut=False)
|
|
py, rs = root / 'py4', root / 'rs4'
|
|
both('mirror ignoring Range', 'fetch', py, rs)
|
|
STATE.update(cut=True)
|
|
py, rs = root / 'py5', root / 'rs5'
|
|
both('mirror cutting the whole file to the range', 'fetch', py, rs)
|
|
STATE.update(ignore_range=False, cut=False)
|
|
server.shutdown()
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
for b in bad:
|
|
print('FAIL', b)
|
|
print(json.dumps({'scenarios': scenarios, 'failures': len(bad), 'oracle': 'tools/mtp_fetch.py (unmodified)'}))
|
|
return 1 if bad else 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
raise SystemExit(main())
|