Files
Athena-Deck/docs/experiments/deepseek-iq2-2026-10-24/prepare.py
T

129 lines
6.4 KiB
Python

#!/usr/bin/env python3
"""Acquire/prepare this isolated experiment. Never starts inference or edits Deck."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import time
ENGINE = 'strata-dsv41-0.1.49.2-linux-x86_64-cuda-cuda13.tar.gz'
ENGINE_SHA = '918a2155ad6bad0ef6d54e57280dfc7cf6fe713838ca9303300bccaebf275283'
SOURCE = '96ca4383c7b05a8a3e6064c65d9e9977d4b3bb59'
def write(base, phase, **extra):
data = dict(phase=phase, updated_at=time.time(), inference_started=False, **extra)
tmp = base / 'preparation-status.json.tmp'
tmp.write_text(json.dumps(data, indent=2) + '\n')
tmp.replace(base / 'preparation-status.json')
print(phase, flush=True)
def run(base, args, log):
with (base / log).open('ab') as out:
subprocess.run(args, cwd=base, stdout=out, stderr=subprocess.STDOUT, check=True)
def download_running(base):
for p in Path('/proc').iterdir():
if not p.name.isdigit():
continue
try:
if (p / 'comm').read_text().strip() != 'aria2c':
continue
if Path(os.readlink(p / 'cwd')) != base:
continue
if b'--input-file=weights.aria2' in (p / 'cmdline').read_bytes().split(b'\0'):
return True
except (FileNotFoundError, ProcessLookupError, PermissionError):
pass
return False
def prepare(base):
manifest = json.loads((base / 'weights-manifest.json').read_text())
got = subprocess.check_output(['git', '-C', str(base / 'source'), 'rev-parse', 'HEAD'], text=True).strip()
if got != SOURCE:
raise RuntimeError('Unexpected isolated source revision')
write(base, 'acquiring_engine_and_weights', source=got)
run(base, ['aria2c', '--continue=true', '--auto-file-renaming=false', '--file-allocation=none',
'--max-connection-per-server=4', '--split=4', '--max-tries=8', '--retry-wait=15',
'--console-log-level=warn', '--summary-interval=60', '--check-integrity=true',
'--checksum=sha-256=' + ENGINE_SHA, '--out=' + ENGINE,
'https://github.com/Niko1221/Strata/releases/download/v0.2.4/' + ENGINE], 'engine-download.log')
if hashlib.file_digest((base / ENGINE).open('rb'), 'sha256').hexdigest() != ENGINE_SHA:
raise RuntimeError('Engine archive hash mismatch')
sys.path.insert(0, str(base / 'source'))
from strata_control.dsv41_engine import install_package
exe = install_package(base / 'engine-dsv41', base / ENGINE)
if exe is None:
raise RuntimeError('Official engine signature/file verification failed')
(base / 'engine-path.txt').write_text(str(exe) + '\n')
write(base, 'waiting_for_weights', engine=str(exe), engine_signed=True)
while download_running(base):
time.sleep(20)
exit_file = base / 'download.exit'
code = exit_file.read_text().strip() if exit_file.exists() else None
if code != '0':
# Resumable recovery if the original SSH/download was interrupted.
write(base, 'resuming_weights', previous_download_exit=code)
run(base, ['aria2c', '--input-file=weights.aria2', '--continue=true',
'--auto-file-renaming=false', '--file-allocation=none', '--max-concurrent-downloads=2',
'--max-connection-per-server=4', '--split=4', '--check-integrity=true',
'--max-tries=8', '--retry-wait=15', '--summary-interval=60',
'--console-log-level=warn'], 'download-resume.log')
exit_file.write_text('0\n')
for row in manifest['files']:
path = base / 'models' / row['name']
if path.stat().st_size != row['size'] or path.with_name(path.name + '.aria2').exists():
raise RuntimeError('Incomplete download: ' + row['name'])
write(base, 'preparing_pack', weights_sha256_verified_by='aria2c checksum + successful exit')
files = [r['name'] for r in manifest['files']]
shards = [n for n in files if 'GSQ-RCO-IQ2_XXS-' in n]
engram = next(n for n in files if 'Engram' in n)
meta = next(n for n in files if 'UD-Q8' in n)
draft = next(n for n in files if n.startswith('dspark-'))
pack = base / 'pack'
args = [sys.executable, str(base / 'source/tools/dsv41/pack_gguf.py'),
'--model', str(base / 'models'), '--shards', *shards,
'--engram', str(base / 'models' / engram), '--engram-meta', str(base / 'models' / meta),
'--dspark-gguf', str(base / 'models' / draft), '--dspark-noise-token', '128799',
'--dspark-markov-rank', '256', '--out', str(pack)]
run(base, args, 'pack.log')
shutil.copyfile(base / 'source/data/dsv41/profile-2.00.bin', pack / 'expert-profile.bin')
run(base, [str(exe), '--pack', str(pack), '--pack-info'], 'pack-info.log')
cfg = dict(exe=str(exe), args=['--pack', str(pack), '--max-context', '8192', '--eos', '1',
'--dspark', 'auto', '--dspark-conf', '0.65', '--tp', '2'],
cwd=str(base / 'source'), tokenizer=str(pack / 'tokenizer'),
model_name='deepseek-v4.1-flash', arch='deepseek41', gpu=[0, 1], gpus_asked=True,
lib_dirs=[str(exe.parent)], host='127.0.0.1', port=19084,
engine_ready_s=3600, open_browser=False, log=str(base / 'test-worker.log'))
(base / 'test-config.json').write_text(json.dumps(cfg, indent=2) + '\n')
if not (base / 'python-ready.txt').exists():
raise RuntimeError('Separate test Python environment is not ready')
run(base, [str(base / 'venv/bin/python'), str(base / 'source/serve/server.py'), '--help'], 'server-help.log')
write(base, 'ready_for_manual_test', engine=str(exe), engine_signed=True,
weights_bytes=manifest['total_bytes'], pack_validated=True,
gpu_inference_tested=False, production_integration=False,
note='No model started. A later explicit test must first safely unload Qwen and restore it afterward.')
if __name__ == '__main__':
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('directory', type=Path)
ap.add_argument('--check-only', action='store_true', help='Read status only, no downloads or preparation.')
a = ap.parse_args()
base = a.directory.resolve()
if a.check_only:
print((base / 'preparation-status.json').read_text() if (base / 'preparation-status.json').exists() else 'Not started')
else:
try:
prepare(base)
except Exception as exc:
write(base, 'failed', error=str(exc))
raise