Files
gloamxun e0feabec8f Initialize optimizer research workspace with official baselines and history-free coverage
Vendor pinned MeZO, AGZO, LOZO and LoREN sources with independent environments. Add direct in-place fix/adjust/node training, derived history-free basis gradients, development-best checkpoints and experiment tooling. Keep models, datasets, caches and credentials outside Git.

Validation: 93 project tests passed; 521 vendored author files verified.
2026-11-12 23:32:33 +08:00

74 lines
6.1 KiB
Python

"""Independent environment and real-model smoke checks, no long training."""
import argparse
import hashlib
from datetime import datetime,timezone
import json
import os
from pathlib import Path
import subprocess
import time
ROOT=Path(__file__).resolve().parents[1]
UV='/home/gloamxun/.local/bin/uv'
ENV=dict(os.environ,UV_SYSTEM_CERTS='true',PYTHONPATH=str(ROOT/'src'),WANDB_MODE='disabled',TOKENIZERS_PARALLELISM='false')
REPORT=ROOT/'reports/validation_report.json'
def save(path,value):
tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(value,indent=2));tmp.replace(path)
def main():
p=argparse.ArgumentParser();p.add_argument('--stage',choices=['native','ours','modern','all'],default='all');p.add_argument('--retry',action='store_true');a=p.parse_args()
results=json.loads(REPORT.read_text())['checks'] if REPORT.exists() else {}
start=time.monotonic()
def run(name,cmd):
files=list((ROOT/'src').rglob('*.py'))+list((ROOT/'methods').rglob('*.py'))+list((ROOT/'tests').rglob('*.py'))
if '_native_' in name:
method=name.split('_')[0];files=[ROOT/'baselines'/method/'native.py',ROOT/'baselines'/method/'uv.lock',ROOT/'src/experiments_codebase/paths.py']
h=hashlib.sha256()
for f in sorted(files):h.update(str(f.relative_to(ROOT)).encode());h.update(f.read_bytes())
fingerprint=h.hexdigest()
if name in results and results[name]['passed'] and results[name].get('source_sha256')==fingerprint and not a.retry:return
print('START',name,flush=True)
log=ROOT/'reports'/f'{name}.log';begin=time.monotonic()
progress=dict(stage='validating',current_unit=name,completed=sum(v['passed'] for v in results.values()),total=None,pid=os.getpid(),output_directory=str(ROOT),last_update=datetime.now(timezone.utc).isoformat(),elapsed_seconds=time.monotonic()-start,log=str(log))
save(ROOT/'reports/progress.json',progress)
tmp=ROOT/'reports/progress.md.tmp';tmp.write_text(f'# Codebase validation\n\nCurrent: {name}\n\nPassed checks: {progress["completed"]}\n\nPID: {os.getpid()}\n\nLog: {log}\n\nUpdated UTC: {progress["last_update"]}\n');tmp.replace(ROOT/'reports/progress.md')
with log.open('w') as stream:
try:rc=subprocess.run(cmd,env=ENV,cwd=ROOT,stdout=stream,stderr=subprocess.STDOUT,timeout=600).returncode
except subprocess.TimeoutExpired:rc=124
results[name]=dict(passed=rc==0,returncode=rc,seconds=time.monotonic()-begin,command=cmd,log=str(log),source_sha256=fingerprint)
save(REPORT,dict(passed=all(v['passed'] for v in results.values()),checks=results,scope='Import/help and small real-model runs; not paper-performance validation',updated=datetime.now(timezone.utc).isoformat()))
print('END',name,rc,flush=True)
if rc:print('\n'.join(log.read_text().splitlines()[-15:]),flush=True)
if a.stage in ('native','all'):
for method in ('mezo','lozo','agzo','loren'):
project=ROOT/'baselines'/method
run(method+'_native_help',[str(project/'.venv/bin/python'),str(project/'native.py'),'--help'])
if method=='loren':
flags='--epochs 1 --samplesize 4 --samplesize_validation 4 --batchsize 2 --batchsize_limit 2 --lr 1e-6 --num_queries 2 --perturbation_scale 1e-3 --damping 0.1 --lr_cov 1e-3 --weight_decay 0 --max_seq_length 64 --logging csv --init_seed 42'.split()
else:
flags='--max_steps 2 --num_train 16 --num_dev 4 --num_eval 4 --per_device_train_batch_size 2 --learning_rate 1e-6 --zo_eps 1e-3 --max_length 64 --save_strategy no --logging_steps 1'.split()
flags+=['--eval_strategy' if method=='agzo' else '--evaluation_strategy','no']
if method=='lozo':flags+=['--rank_r','1','--step_interval','100']
run(method+'_native_opt_sst2',[str(project/'.venv/bin/python'),str(project/'native.py'),'--asset-model','facebook/opt-1.3b','--asset-task','sst2',*flags])
if a.stage in ('ours','all'):
run('mechanism_tests',[str(ROOT/'.venv/bin/python'),'-m','pytest','-q','tests'])
for method in ('fix','adjust','node'):
for model in ('facebook/opt-1.3b','Qwen/Qwen3-0.6B'):
for task in ('sst2','drop'):
entry=ROOT/'methods/large_models/run.py'
flags=['--method',method,'--model',model,'--task',task,'--budget',str({'fix':5,'adjust':17,'node':17}[method]),'--refresh-every','1','--train-samples','8','--dev-samples','2','--eval-samples','2','--batch-size','2','--eval-batch-size','2','--calibration-samples','2','--max-length','64','--eval-every','100','--no-save-checkpoint']
run(f'{method}_{model.split("/")[-1]}_{task}',[str(ROOT/'.venv/bin/python'),str(entry),*flags])
if a.stage in ('modern','all'):
for method in ('mezo','lozo','agzo','loren'):
project=ROOT/'baselines'/method
run(method+'_modern_sync',[UV,'sync','--locked','--project',str(project),'--no-default-groups','--group','modern'])
for model in ('facebook/opt-1.3b','Qwen/Qwen3-0.6B'):
for task in ('sst2','drop'):
flags=['--model',model,'--task',task,'--budget','6','--train-samples','8','--dev-samples','2','--eval-samples','2','--batch-size','2','--eval-batch-size','2','--max-length','64','--eval-every','100','--no-save-checkpoint']
run(f'{method}_compatible_{model.split("/")[-1]}_{task}',[str(project/'.venv/bin/python'),str(project/'run_compatible.py'),*flags])
run(method+'_restore_native',[UV,'sync','--locked','--project',str(project)])
report=json.loads(REPORT.read_text())
progress=dict(stage='complete' if report['passed'] else 'needs_fixes',completed=sum(v['passed'] for v in results.values()),total=len(results),pid=os.getpid(),last_update=datetime.now(timezone.utc).isoformat(),output_directory=str(ROOT),elapsed_seconds=time.monotonic()-start)
save(ROOT/'reports/progress.json',progress)
(ROOT/'reports/progress.md').write_text('# Codebase validation\n\n'+json.dumps(progress,indent=2)+'\n\nSee validation_report.json for exact scope and per-check logs. No commits/pushes.\n')
if __name__=='__main__':main()