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.
This commit is contained in:
commit
e0feabec8f
596 files changed
+87356
No files matched your search
@@ -0,0 +1,105 @@
|
||||
{
|
||||
"models": {
|
||||
"facebook/opt-1.3b": {
|
||||
"path": "/mnt/e/Experiments/Assets/models/opt-1.3b",
|
||||
"revision": "3f5c25d0bc631cb57ac65913f76e22c2dfb61d62",
|
||||
"files": {
|
||||
"config.json": {
|
||||
"bytes": 653,
|
||||
"sha256": "f1aaceefb7d34d346e9b0400d95fdb4970567bcbe1d4aba1068c5402099b644f"
|
||||
},
|
||||
"generation_config.json": {
|
||||
"bytes": 137,
|
||||
"sha256": "d37de99f9835d7a4d0916257f724504d12c4a668f36a50b2d42e09ba4ebd05d5"
|
||||
},
|
||||
"merges.txt": {
|
||||
"bytes": 456318,
|
||||
"sha256": "1ce1664773c50f3e0cc8842619a93edc4624525b728b188a9e0be33b7726adc5"
|
||||
},
|
||||
"pytorch_model.bin": {
|
||||
"bytes": 2631639353,
|
||||
"sha256": "cf7d5c970d6ddbd3b03009b397c0422e147edd5c8020d47a8d2fac0b11a3b08d"
|
||||
},
|
||||
"special_tokens_map.json": {
|
||||
"bytes": 441,
|
||||
"sha256": "0f3cd5f307a2735cfee31ddf33be88655e8be165ee2cdc26ced966f04258adf0"
|
||||
},
|
||||
"tokenizer_config.json": {
|
||||
"bytes": 685,
|
||||
"sha256": "d1e4185b43a0a06421ab7218d5c1a775350bd13024507b34fbed25dcf6c14c6b"
|
||||
},
|
||||
"vocab.json": {
|
||||
"bytes": 898822,
|
||||
"sha256": "06b4d46c8e752d410213d9548eb27a54db70fda0319b6271fb8d59dead5e1cab"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Qwen/Qwen3-0.6B": {
|
||||
"path": "/mnt/e/Experiments/Assets/models/qwen3-0.6b",
|
||||
"revision": "c1899de289a04d12100db370d81485cdf75e47ca",
|
||||
"files": {
|
||||
"LICENSE": {
|
||||
"bytes": 11343,
|
||||
"sha256": "832dd9e00a68dd83b3c3fb9f5588dad7dcf337a0db50f7d9483f310cd292e92e"
|
||||
},
|
||||
"README.md": {
|
||||
"bytes": 13965,
|
||||
"sha256": "1ab64a26fcb3b461423b89a433a8c858f1bf8d4086f979cbb3ff878d47cf20e9"
|
||||
},
|
||||
"config.json": {
|
||||
"bytes": 726,
|
||||
"sha256": "660db3b73d788119c04535e48cf9be5f55bc3100841a718637ae695b442f27dd"
|
||||
},
|
||||
"generation_config.json": {
|
||||
"bytes": 239,
|
||||
"sha256": "2325da0f15bb848e018c5ae071b7943332e9f871d6b60e2ed22ca97d4cb993d2"
|
||||
},
|
||||
"merges.txt": {
|
||||
"bytes": 1671853,
|
||||
"sha256": "8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5"
|
||||
},
|
||||
"model.safetensors": {
|
||||
"bytes": 1503300328,
|
||||
"sha256": "f47f71177f32bcd101b7573ec9171e6a57f4f4d31148d38e382306f42996874b"
|
||||
},
|
||||
"tokenizer.json": {
|
||||
"bytes": 11422654,
|
||||
"sha256": "aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4"
|
||||
},
|
||||
"tokenizer_config.json": {
|
||||
"bytes": 9732,
|
||||
"sha256": "d5d09f07b48c3086c508b30d1c9114bd1189145b74e982a265350c923acd8101"
|
||||
},
|
||||
"vocab.json": {
|
||||
"bytes": 2776833,
|
||||
"sha256": "ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"datasets": {
|
||||
"sst2": {
|
||||
"path": "/mnt/e/Experiments/Assets/data/sst2",
|
||||
"rows": {
|
||||
"train": 67349,
|
||||
"validation": 872
|
||||
},
|
||||
"fingerprints": {
|
||||
"train": "31164fe5d5d3c937",
|
||||
"validation": "85a5492b887544af"
|
||||
}
|
||||
},
|
||||
"drop": {
|
||||
"path": "/mnt/e/Experiments/Assets/data/drop",
|
||||
"rows": {
|
||||
"train": 77400,
|
||||
"validation": 9535
|
||||
},
|
||||
"fingerprints": {
|
||||
"train": "758c6e093d1e3b41",
|
||||
"validation": "77842021869200ba"
|
||||
}
|
||||
}
|
||||
},
|
||||
"note": "File hashes pin staged models; datasets fingerprints are serialization-specific, run data hashes are authoritative."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Inspect the active uv environment and shared assets without loading model weights."""
|
||||
import importlib.metadata as meta
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'src'))
|
||||
from experiments_codebase.paths import paths
|
||||
import torch
|
||||
from datasets import load_from_disk
|
||||
result={'python':sys.version,'executable':sys.executable,'paths':{k:str(v) for k,v in paths().items()},'versions':{p:meta.version(p) for p in ('torch','transformers','datasets','huggingface-hub')},'cuda_available':torch.cuda.is_available()}
|
||||
if torch.cuda.is_available():
|
||||
x=torch.ones(1,device='cuda');result.update(gpu=torch.cuda.get_device_name(),capability=torch.cuda.get_device_capability(),cuda_smoke=float((x+x).cpu()))
|
||||
for task in ('sst2','drop'):
|
||||
ds=load_from_disk(str(paths()['data']/task));result[task]={s:len(d) for s,d in ds.items()}
|
||||
print(json.dumps(result,indent=2))
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
# Source from any directory; no activation of another project's environment.
|
||||
_experiments_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
if [ -f "$_experiments_root/.env" ]; then
|
||||
set -a; source "$_experiments_root/.env"; set +a
|
||||
fi
|
||||
export EXPERIMENT_ASSETS="${EXPERIMENT_ASSETS:-/mnt/e/Experiments/Assets}"
|
||||
export EXPERIMENT_MODELS="${EXPERIMENT_MODELS:-$EXPERIMENT_ASSETS/models}"
|
||||
export EXPERIMENT_DATA="${EXPERIMENT_DATA:-$EXPERIMENT_ASSETS/data}"
|
||||
export EXPERIMENT_RESULTS="${EXPERIMENT_RESULTS:-$EXPERIMENT_ASSETS/results}"
|
||||
# Override legacy HF_HOME inherited from older experiments within this shell.
|
||||
export HF_HOME="$EXPERIMENT_MODELS/.huggingface"
|
||||
export HF_HUB_CACHE="$HF_HOME/hub"
|
||||
export HF_DATASETS_CACHE="$EXPERIMENT_DATA/.huggingface/datasets"
|
||||
export HF_XET_CACHE="$HF_HOME/xet"
|
||||
export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}"
|
||||
export WANDB_DIR="$EXPERIMENT_RESULTS/wandb"
|
||||
export WANDB_MODE="${WANDB_MODE:-disabled}"
|
||||
export TOKENIZERS_PARALLELISM=false
|
||||
export PYTHONPATH="$_experiments_root/src${PYTHONPATH:+:$PYTHONPATH}"
|
||||
unset _experiments_root
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Final checks of environments, assets, provenance and the uncommitted tree."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from datetime import datetime,timezone
|
||||
ROOT=Path(__file__).resolve().parents[1];UV=str(Path.home()/'.local/bin/uv')
|
||||
reports=ROOT/'reports'
|
||||
results={}
|
||||
with (reports/'dependency_check.log').open('w') as log:
|
||||
for name,folder in [('ours',ROOT),*[(m,ROOT/'baselines'/m) for m in ('mezo','agzo','lozo','loren')]]:
|
||||
log.write(f'\n=== {name} ===\n');log.flush()
|
||||
process=subprocess.run([UV,'pip','check','--python',str(folder/'.venv/bin/python')],stdout=log,stderr=subprocess.STDOUT)
|
||||
assert process.returncode==0,name
|
||||
path=reports/f'{name}_environment.json'
|
||||
data=subprocess.check_output([str(folder/'.venv/bin/python'),str(ROOT/'scripts/doctor.py')],text=True)
|
||||
path.write_text(data);results[name]=json.loads(data)
|
||||
assert results[name]['sst2']['train']==67349 and results[name]['drop']['train']==77400
|
||||
for m in ('mezo','agzo','lozo','loren'):
|
||||
for required in ('pyproject.toml','uv.lock','.python-version','TROUBLESHOOTING.md','native.py','run_compatible.py'):
|
||||
assert (ROOT/'baselines'/m/required).is_file()
|
||||
validation=json.loads((reports/'validation_report.json').read_text())
|
||||
assert validation['passed'] and len(validation['checks'])==45
|
||||
checkpoint=json.loads((reports/'checkpoint_restore.json').read_text())
|
||||
assert checkpoint['passed']
|
||||
source=json.loads((reports/'source_audit.json').read_text())
|
||||
assert all(not v['tracked_upstream_changes'] for v in source['official_sources'].values())
|
||||
assert subprocess.check_output(['git','-C',str(ROOT),'rev-list','--all','--count'],text=True).strip()=='0'
|
||||
assert not subprocess.check_output(['git','-C',str(ROOT),'diff','--cached','--name-only'],text=True).strip()
|
||||
ignored=['.env','.venv/bin/python','baselines/mezo/.venv/bin/python','baselines/mezo/.upstream-git/config','models/test.bin','data/test.parquet','results/test.json']
|
||||
check=subprocess.run(['git','-C',str(ROOT),'check-ignore','--stdin'],input='\n'.join(ignored)+'\n',capture_output=True,text=True,check=True)
|
||||
assert check.stdout.splitlines()==ignored
|
||||
result=dict(passed=True,checked_at=datetime.now(timezone.utc).isoformat(),validation_checks=45,mechanism_tests=5,checkpoint_roundtrip=checkpoint,
|
||||
environments=results,git=dict(commits=0,staged_files=0,official_source_changes=0),
|
||||
scope='Small real-model independent execution, dependency and inference checks; no full benchmark or paper accuracy reproduction',
|
||||
final_environment_change='HF defaults initialized before library imports; final modern model/task matrix, doctor in all five environments, mechanism tests and checkpoint roundtrip validate this routing change.')
|
||||
(reports/'final_audit.json').write_text(json.dumps(result,indent=2))
|
||||
progress=dict(stage='complete',completed=45,total=45,current_unit='Packaging, independent environments and smoke validation complete',last_update=result['checked_at'],output_directory=str(ROOT),no_commit_or_push=True)
|
||||
tmp=reports/'progress.json.tmp';tmp.write_text(json.dumps(progress,indent=2));tmp.replace(reports/'progress.json')
|
||||
tmp=reports/'progress.md.tmp';tmp.write_text('# Preparation complete\n\n45 independent checks passed; 5 numerical mechanism tests passed. Checkpoint reload, evaluation and generation passed. Five independent uv environments pass dependency checks and read both datasets.\n\nNo commit or push; no full benchmark launched.\n\nSee final_audit.json and validation_report.json for scope and exact logs.\n');tmp.replace(reports/'progress.md')
|
||||
print(json.dumps({'passed':True,'validation_checks':45,'environments':list(results),'root':str(ROOT)}))
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Compare selected compatible run curves without seed-range shading."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'src'))
|
||||
from experiments_codebase.paths import paths
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--config',type=Path,required=True);p.add_argument('--out',type=Path,required=True);a=p.parse_args()
|
||||
if not a.out.resolve().is_relative_to(paths()['results'].resolve()):raise ValueError('Plots belong under shared results')
|
||||
a.out.mkdir(parents=True,exist_ok=True);cfg=json.loads(a.config.read_text())
|
||||
for metric in ('loss','accuracy'):
|
||||
fig,ax=plt.subplots(figsize=(9,4));any_curve=False
|
||||
for item in cfg['runs']:
|
||||
if not item.get('enabled',True):continue
|
||||
folder=Path(item['directory']);curve=json.loads((folder/'curve.json').read_text());split=cfg.get('split','development')
|
||||
points=[v for v in curve if metric in v[split]]
|
||||
if points:ax.plot([v['main_forwards'] for v in points],[v[split][metric] for v in points],label=item['label']);any_curve=True
|
||||
if any_curve:
|
||||
ax.set(xlabel='Cumulative main forwards',ylabel=metric,title=cfg.get('title',''));ax.legend();ax.grid(alpha=.2);fig.tight_layout();fig.savefig(a.out/f'{metric}_curve.png',dpi=180)
|
||||
plt.close(fig)
|
||||
(a.out/'plot_config.json').write_text(json.dumps(cfg,indent=2))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"title": "OPT-1.3B / SST-2",
|
||||
"split": "development",
|
||||
"runs": [
|
||||
{
|
||||
"label": "MeZO",
|
||||
"directory": "/mnt/e/Experiments/Assets/results/REPLACE_MEZO_RUN",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"label": "Adjust",
|
||||
"directory": "/mnt/e/Experiments/Assets/results/REPLACE_ADJUST_RUN",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"label": "Node",
|
||||
"directory": "/mnt/e/Experiments/Assets/results/REPLACE_NODE_RUN",
|
||||
"enabled": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Copy verified existing assets, or explicitly download absent public assets. No moves."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser();p.add_argument('--download-missing',action='store_true');p.add_argument('--datasets-only',action='store_true');a=p.parse_args()
|
||||
subprocess.run(['mountpoint','-q','/mnt/e'],check=True)
|
||||
root=Path(os.environ.get('EXPERIMENT_ASSETS','/mnt/e/Experiments/Assets'))
|
||||
old=Path('/mnt/e/Experiments/optimizer_research')
|
||||
root.mkdir(parents=True,exist_ok=True)
|
||||
for d in ('models','data','results'):(root/d).mkdir(exist_ok=True)
|
||||
os.environ['HF_HOME']=str(root/'models/.huggingface')
|
||||
os.environ['HF_HUB_CACHE']=str(root/'models/.huggingface/hub')
|
||||
os.environ['HF_DATASETS_CACHE']=str(root/'data/.huggingface/datasets')
|
||||
os.environ['HF_XET_CACHE']=str(root/'models/.huggingface/xet')
|
||||
manifest=json.loads((root/'asset_manifest.json').read_text()) if (root/'asset_manifest.json').exists() else {'root':str(root),'models':{},'datasets':{}}
|
||||
lockpath=Path(__file__).with_name('assets.lock.json')
|
||||
lock=json.loads(lockpath.read_text()) if lockpath.exists() else {}
|
||||
for ident,alias in ([] if a.datasets_only else [('facebook/opt-1.3b','opt-1.3b'),('Qwen/Qwen3-0.6B','qwen3-0.6b')]):
|
||||
dest=root/'models'/alias;dest.mkdir(exist_ok=True)
|
||||
cache=old/'huggingface/hub'/('models--'+ident.replace('/','--'))/'snapshots'
|
||||
candidates=sorted(cache.glob('*')) if cache.exists() else []
|
||||
expected=lock.get('models',{}).get(ident,{})
|
||||
snapshots=[v for v in candidates if (v/'config.json').exists() and (not expected or v.name==expected['revision'])]
|
||||
if snapshots:
|
||||
source=snapshots[-1];revision=source.name
|
||||
for f in source.rglob('*'):
|
||||
if not f.is_file():continue
|
||||
target=dest/f.relative_to(source);target.parent.mkdir(parents=True,exist_ok=True)
|
||||
if not target.exists():shutil.copy2(f,target,follow_symlinks=True)
|
||||
if target.stat().st_size!=f.stat().st_size:raise RuntimeError(f'Partial asset {target}')
|
||||
elif a.download_missing:
|
||||
from huggingface_hub import snapshot_download
|
||||
snapshot_download(ident,revision=expected.get('revision','main'),local_dir=dest);revision=expected.get('revision','downloaded: see local HF metadata')
|
||||
else:raise RuntimeError(f'No cached model {ident}; retry with --download-missing')
|
||||
files={}
|
||||
for f in sorted(dest.rglob('*')):
|
||||
if not f.is_file() or '.cache' in f.parts:continue
|
||||
h=hashlib.sha256()
|
||||
with f.open('rb') as stream:
|
||||
for block in iter(lambda:stream.read(8*1024*1024),b''):h.update(block)
|
||||
files[str(f.relative_to(dest))]={'bytes':f.stat().st_size,'sha256':h.hexdigest()}
|
||||
pinned=expected.get('files',{}).get(str(f.relative_to(dest)))
|
||||
if pinned and files[str(f.relative_to(dest))]!=pinned:raise RuntimeError(f'Model hash mismatch: {f}')
|
||||
manifest['models'][ident]={'path':str(dest),'revision':revision,'files':files}
|
||||
print(f'Model ready: {ident} ({len(files)} files)',flush=True)
|
||||
# Preserve raw full datasets separately from frozen historical benchmark samples.
|
||||
from datasets import load_dataset, DatasetDict
|
||||
for ident,config,alias in [('glue','sst2','sst2'),('ucinlp/drop',None,'drop')]:
|
||||
dest=root/'data'/alias
|
||||
from datasets import load_from_disk
|
||||
try:
|
||||
ds=load_from_disk(str(dest)) if (dest/'dataset_dict.json').exists() else None
|
||||
except ValueError:
|
||||
# Rebuild from immutable raw parquet when a newer datasets serialized List
|
||||
# features that legacy author environments cannot read.
|
||||
ds=None
|
||||
if ds is None:
|
||||
if alias=='sst2' and (old/'datasets/sst2/train.parquet').exists():
|
||||
ds=load_dataset('parquet',data_files={s:str(old/f'datasets/sst2/{s}.parquet') for s in ('train','validation')})
|
||||
else:
|
||||
hub=old/'huggingface/hub'/('datasets--'+ident.replace('/','--'))/'snapshots'
|
||||
parquet={s:sorted(str(f) for v in hub.glob('*') for f in v.rglob(f'*{s}*.parquet')) for s in ('train','validation')}
|
||||
if all(parquet.values()):ds=load_dataset('parquet',data_files=parquet)
|
||||
elif a.download_missing:ds=load_dataset(ident,config) if config else load_dataset(ident)
|
||||
else:raise RuntimeError(f'No cached raw {alias}; retry with --download-missing')
|
||||
ds.save_to_disk(str(dest))
|
||||
from datasets import load_from_disk
|
||||
ds=load_from_disk(str(dest))
|
||||
manifest['datasets'][alias]={'path':str(dest),'rows':{s:len(d) for s,d in ds.items()},
|
||||
'fingerprints':{s:d._fingerprint for s,d in ds.items()}}
|
||||
print(f'Dataset ready: {alias} {manifest["datasets"][alias]["rows"]}',flush=True)
|
||||
frozen=old/'results/final_results/data'
|
||||
if frozen.exists():
|
||||
shutil.copytree(frozen,root/'data/historical_opt13_sst2',dirs_exist_ok=True)
|
||||
target=root/'asset_manifest.json';tmp=target.with_suffix('.tmp');tmp.write_text(json.dumps(manifest,indent=2));tmp.replace(target)
|
||||
print(f'Manifest: {target}')
|
||||
|
||||
if __name__=='__main__':main()
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
uv sync --locked
|
||||
for method in mezo agzo lozo loren; do
|
||||
uv sync --locked --project "baselines/$method"
|
||||
done
|
||||
@@ -0,0 +1,73 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Small real-model save/reload/inference check; outputs remain in shared Assets."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime,timezone
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'src'))
|
||||
from experiments_codebase.paths import paths,save
|
||||
|
||||
def main():
|
||||
stamp=datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
|
||||
output=paths()['results']/f'checkpoint_check_{stamp}'
|
||||
import argparse
|
||||
cached=list(Path('/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots').glob('*/config.json'))
|
||||
parser=argparse.ArgumentParser();parser.add_argument('--model',default=str(cached[0].parent) if cached else 'Qwen/Qwen3-0.6B')
|
||||
model=parser.parse_args().model
|
||||
args=['--model',model,'--task','sst2','--budget','5','--train-samples','8','--dev-samples','2','--eval-samples','2','--batch-size','2','--eval-batch-size','2','--calibration-samples','2','--max-length','64']
|
||||
entry=ROOT/'methods/large_models/run.py';train=output/'training';evaluation=output/'evaluation';generation=output/'generation'
|
||||
output.mkdir()
|
||||
commands=[['--out',str(train),*args],['--action','evaluate','--checkpoint',str(train/'model'),'--out',str(evaluation),*args],['--action','generate','--checkpoint',str(train/'model'),'--out',str(generation),'--prompt','A wonderful movie It was','--max-new-tokens','4',*args]]
|
||||
for index,flags in enumerate(commands):
|
||||
with (output/f'{index}.log').open('w') as stream:subprocess.run([sys.executable,str(entry),*flags],cwd=ROOT,stdout=stream,stderr=subprocess.STDOUT,check=True,timeout=300)
|
||||
before=json.loads((train/'summary.json').read_text())['validation'];after=json.loads((evaluation/'evaluation.json').read_text())
|
||||
assert before['accuracy']==after['accuracy'] and abs(before['loss']-after['loss'])<5e-5
|
||||
save(ROOT/'reports/mezo_refactor/checkpoint_restore.json',dict(passed=True,model=model,task='sst2',before=before,after=after,output=str(output),generation=json.loads((generation/'generation.json').read_text()),scope='Small real-model training checkpoint, merged HF weight restoration (FP32 rounding tolerance), evaluation and generation; not performance evidence'))
|
||||
print(json.dumps({'passed':True,'output':str(output)}))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,56 @@
|
||||
"""CPU FP64 quadrature audit of actual forward queries; never launches training."""
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(ROOT), str(ROOT/'src'), str(ROOT/'tests')]
|
||||
from test_history_free_coverage import quadrature
|
||||
|
||||
|
||||
def main():
|
||||
if not os.path.ismount('/mnt/e'):
|
||||
raise RuntimeError('Shared E mount is unavailable')
|
||||
out = Path('/mnt/e/Experiments/Assets/results')/(
|
||||
'history_free_coverage_audit_'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
|
||||
out.mkdir(parents=True, exist_ok=False)
|
||||
results = dict(protocol='analytic small-model validation; no LLM training',
|
||||
dtype='float64', quadrature_order=4, gaussian_dimensions=2,
|
||||
sign_patterns=16, draws_per_case=256, forwards_per_draw=3,
|
||||
training_queries=0, evaluation_queries=0, cases={}, bias={})
|
||||
diagnostic = 0
|
||||
for power in (1, 2):
|
||||
r = quadrature(power)
|
||||
diagnostic += r['forwards']
|
||||
results['cases'][str(power)] = dict(max_error=r['max_error'],
|
||||
tangent_error=r['max_tangent'],
|
||||
mean={n: v.flatten().tolist() for n, v in r['mean'].items()},
|
||||
truth={n: v.flatten().tolist() for n, v in r['truth'].items()})
|
||||
assert r['max_error'] < 1e-11
|
||||
for varying in ('mu', 'eps'):
|
||||
errors = []
|
||||
for radius in (.08, .04, .02):
|
||||
kwargs = dict(mu=1e-5, eps=1e-5)
|
||||
kwargs[varying] = radius
|
||||
r = quadrature(4, **kwargs)
|
||||
diagnostic += r['forwards']
|
||||
errors.append(r['max_error'])
|
||||
ratios = [errors[i]/errors[i+1] for i in range(2)]
|
||||
assert all(3.8 < ratio < 4.2 for ratio in ratios)
|
||||
results['bias'][varying] = dict(radii=[.08, .04, .02], errors=errors, ratios=ratios)
|
||||
results['diagnostic_forward_queries'] = diagnostic
|
||||
files = ['methods/large_models/trainer.py', 'methods/HISTORY_FREE_COVERAGE.md',
|
||||
'tests/test_history_free_coverage.py', 'scripts/validate_history_free_coverage.py']
|
||||
results['sources'] = {n: hashlib.sha256((ROOT/n).read_bytes()).hexdigest() for n in files}
|
||||
results['command'] = '.venv/bin/python scripts/validate_history_free_coverage.py'
|
||||
results['status'] = 'passed'
|
||||
(out/'validation.json').write_text(json.dumps(results, indent=2)+'\n')
|
||||
print(json.dumps(dict(output=str(out), cases=results['cases'], bias=results['bias'],
|
||||
diagnostic_forward_queries=diagnostic), indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Verify vendored author files even after cloning the outer project without upstream Git objects."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
manifest=json.loads((ROOT/'upstream_files.sha256.json').read_text())
|
||||
checked=0
|
||||
for method,entry in manifest.items():
|
||||
for name,expected in entry['files'].items():
|
||||
path=ROOT/'baselines'/method/name
|
||||
assert path.is_file(),f'Missing official file: {path}'
|
||||
assert hashlib.sha256(path.read_bytes()).hexdigest()==expected,f'Modified official file: {path}'
|
||||
checked+=1
|
||||
print(json.dumps({'passed':True,'official_files_checked':checked}))
|
||||
Reference in new issue
Block a user