Files
experiments_codebase/baselines/lozo/native.py
T
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

72 lines
4.6 KiB
Python

"""Run the original entry point with shared local assets. No optimizer rewrite."""
import argparse
from datetime import datetime,timezone
import json
import os
from pathlib import Path
import runpy
import sys
HERE=Path(__file__).resolve().parent
ROOT=HERE.parents[1]
sys.path.insert(0,str(ROOT/'src'))
from experiments_codebase.paths import paths,model_path,save
def main():
p=argparse.ArgumentParser(description=__doc__,add_help=False)
p.add_argument('--asset-model',default='facebook/opt-1.3b')
p.add_argument('--asset-task',choices=['sst2','drop'],default='sst2')
p.add_argument('--asset-out',type=Path)
args,rest=p.parse_known_args();method=HERE.name
roots=paths();os.environ.setdefault('WANDB_MODE','disabled');os.environ['WANDB_DIR']=str(roots['results']/'wandb')
out=(args.asset_out or roots['results']/f'native_{method}_{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}').resolve()
if not out.is_relative_to(roots['results'].resolve()):raise ValueError('Output must be under shared results')
# Both local datasets are supplied through the HF Dataset API expected by authors.
import datasets
original=datasets.load_dataset
def local_dataset(name,*pos,**kw):
config=pos[0] if pos else kw.get('name')
alias='sst2' if (name in ('glue','nyu-mll/glue') and config=='sst2') or name=='sst2' else ('drop' if name in ('drop','ucinlp/drop') else None)
if alias:
ds=datasets.load_from_disk(str(roots['data']/alias))
split=kw.get('split');return ds[split] if split else ds
return original(name,*pos,**kw)
datasets.load_dataset=local_dataset
model=str(model_path(args.asset_model))
if method=='loren':
if args.asset_task=='drop':raise ValueError('Official LOREN has no DROP task; use run_compatible.py with the modern group for a labeled task extension')
if 'Qwen' in args.asset_model:raise ValueError('Official LOREN has no Qwen model branch; use the modern compatibility entry')
entry=HERE/'main.py'
defaults=['--model_name',model,'--task',args.asset_task,'--algorithm','LOREN','--results',str(out),'--full_parameter']
else:
work=HERE/('zo-bench' if method=='agzo' else 'large_models')
entry=work/('run_lozo.py' if method=='lozo' else 'run.py')
task='SST2' if args.asset_task=='sst2' else 'DROP'
defaults=['--model_name',model,'--task_name',task,'--output_dir',str(out),'--trainer',{'mezo':'zo','lozo':'LOZO','agzo':'agzo'}[method],
'--report_to','none','--train_set_seed','42','--train_as_classification',str(task=='SST2'),'--lr_scheduler_type','constant']
defaults+=['--result_file',str(out/'result.json')]
# User's original HF/author flags appear last and override wrapper defaults.
if '--help' not in rest:
out.mkdir(parents=True,exist_ok=False)
save(out/'launch.json',dict(method=method,entry=str(entry),argv=defaults+rest,executable=sys.executable,adapter='Local assets and paths only; original Trainer/optimizer',pid=os.getpid()))
sys.path.insert(0,str(entry.parent));os.chdir(out if out.exists() else HERE)
sys.argv=[str(entry),*defaults,*rest]
if method=='agzo':
import torch
if torch.cuda.is_available() and not hasattr(torch,'npu'):
# The author's NPU helper has incomplete CUDA branches. Only device
# plumbing is adapted; trainer.py and AGZO numerical methods are intact.
import npu_compat as devices
devices.device_count=torch.cuda.device_count
devices.mem_get_info=torch.cuda.mem_get_info
devices.get_active_device_info=lambda:('cuda',torch.cuda.current_device(),torch.cuda.get_device_properties(0).total_memory/2**30,torch.cuda.get_device_name())
devices.safe_set_device=lambda index:(torch.cuda.set_device(int(index or 0)) or int(index or 0),torch.cuda.device_count())
devices.to_device=lambda tensor:tensor.cuda()
source=entry.read_text().replace('torch.npu.manual_seed_all(seed)','torch.cuda.manual_seed_all(seed)').replace('torch.npu.device_count()','torch.cuda.device_count()')
if out.exists():save(out/'compatibility_changes.json',{'scope':'CUDA device plumbing only','source_modified_on_disk':False,'numerical_optimizer_modified':False,'changes':['NPU seed -> CUDA seed','NPU device count -> CUDA count','device helper memory/info/count/set/to_device CUDA callbacks']})
exec(compile(source,str(entry),'exec'),dict(__name__='__main__',__file__=str(entry)))
return
runpy.run_path(str(entry),run_name='__main__')
if __name__=='__main__':main()