aaaded's picture
Publish complete 32-run capacity-boundary evaluation and reproducibility evidence
b93475d verified
Raw History Blame Contribute Delete
6.76 kB
"""Run the predeclared local experiment; no paid services. MIT."""
import argparse
import datetime
import hashlib
import importlib.metadata
import json
import os
import platform
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent
os.environ['HF_HOME'] = str(ROOT/'hf-cache')
os.environ['HF_HUB_OFFLINE'] = '1'
os.environ['HF_HUB_DISABLE_IMPLICIT_TOKEN'] = '1'
os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1'
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
os.environ['OMP_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'
from study import score, SEED
def sha(path):
with path.open('rb') as stream:
return hashlib.file_digest(stream,'sha256').hexdigest()
def main():
parser=argparse.ArgumentParser()
parser.add_argument('--smoke-only',action='store_true')
args=parser.parse_args()
print('Importing runtime libraries',flush=True)
import torch
from transformers import AutoModelForCausalLM,AutoTokenizer,GenerationConfig
print('Runtime imported; checking CUDA and artifact hashes',flush=True)
if not torch.cuda.is_available():
raise RuntimeError('CUDA unavailable; no silent CPU or paid-cloud fallback')
if not torch.cuda.is_bf16_supported():
raise RuntimeError('BF16 unsupported; protocol needs an explicit revision')
torch.set_num_threads(1)
torch.manual_seed(SEED)
torch.cuda.manual_seed_all(SEED)
torch.backends.cuda.matmul.allow_tf32=False
torch.backends.cudnn.allow_tf32=False
torch.use_deterministic_algorithms(True,warn_only=True)
metadata=json.loads((ROOT/'model-artifacts.json').read_text(encoding='utf-8'))
for file in metadata['files']:
path=ROOT/'model'/file['file']
if sha(path)!=file['sha256']:
raise RuntimeError('Local artifact changed: '+file['file'])
corpus=json.loads((ROOT/'corpus.json').read_text(encoding='utf-8'))
env=dict(model=metadata['model'],revision=metadata['revision'],python=platform.python_version(),
os=platform.system(),torch=torch.__version__,cuda=torch.version.cuda,gpu=torch.cuda.get_device_name(0),
dtype='bfloat16',batch_size=1,seed=SEED,max_new_tokens=1536,do_sample=False,
device_map='cuda:0',cpu_threads=1,
corpus_sha256=sha(ROOT/'corpus.json'),protocol_sha256=sha(ROOT/'PROTOCOL.md'),
runner_sha256=sha(Path(__file__)),scorer_sha256=sha(ROOT/'study.py'),
packages={n:importlib.metadata.version(n) for n in ('transformers','huggingface-hub','tokenizers','safetensors','accelerate')},
started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),cash_expense=0,
determinism='Fixed seeds, greedy decoding, deterministic algorithms warn_only; exact cross-hardware identity not guaranteed')
tokenizer=AutoTokenizer.from_pretrained(str(ROOT/'model'),trust_remote_code=True,local_files_only=True)
print('Loading pinned original BF16 weights',flush=True)
model=AutoModelForCausalLM.from_pretrained(str(ROOT/'model'),trust_remote_code=True,local_files_only=True,dtype=torch.bfloat16,device_map='cuda:0').eval()
generation=GenerationConfig(do_sample=False,max_new_tokens=1536,use_cache=True,
bos_token_id=tokenizer.bos_token_id,eos_token_id=tokenizer.eos_token_id,pad_token_id=tokenizer.pad_token_id)
effective,_=model._prepare_generation_config(generation,use_model_defaults=False,do_sample=False,max_new_tokens=1536)
if effective.do_sample or effective.num_beams!=1 or effective.max_new_tokens!=1536:
raise RuntimeError('Resolved generation config differs from frozen greedy protocol')
env['effective_generation_config']=effective.to_dict()
env['use_model_defaults']=False
print('Resolved generation mode:',effective.get_generation_mode(),flush=True)
def generate(prompt,thinking,budget):
rendered=tokenizer.apply_chat_template([dict(role='user',content=prompt)],tokenize=False,add_generation_prompt=True,enable_thinking=thinking)
tokens=tokenizer(rendered,return_tensors='pt',add_special_tokens=False).to('cuda')
torch.cuda.synchronize();torch.cuda.reset_peak_memory_stats();start=time.perf_counter()
with torch.inference_mode():
output=model.generate(**tokens,generation_config=generation,use_model_defaults=False,do_sample=False,max_new_tokens=budget)
torch.cuda.synchronize()
ids=output[0,tokens['input_ids'].shape[1]:].tolist()
text=tokenizer.decode(ids,skip_special_tokens=False)
eos=tokenizer.eos_token_id
finished=bool(ids and ids[-1]==eos)
# Keep full raw text; only the terminal EOS token is removed for scoring.
scored_text=tokenizer.decode(ids[:-1] if finished else ids,skip_special_tokens=False)
return dict(rendered_prompt=rendered,input_ids=tokens['input_ids'][0].tolist(),output_ids=ids,
output=text,scoring_text=scored_text,input_tokens=tokens['input_ids'].shape[1],output_tokens=len(ids),
seconds=time.perf_counter()-start,peak_allocated_bytes=torch.cuda.max_memory_allocated(),
ended_with_eos=finished,truncated=not finished and len(ids)>=budget)
smoke=generate('What is 2+3? Reply with only the number.',False,64)
(ROOT/'smoke.json').write_text(json.dumps(dict(environment=env,result=smoke),ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print('Smoke:',repr(smoke['output']),f"{smoke['seconds']:.1f}s",flush=True)
if args.smoke_only:
return
output_path=ROOT/'runs.jsonl'
if output_path.exists():
raise RuntimeError('Measured run file already exists; do not silently repeat/select runs')
(ROOT/'environment.json').write_text(json.dumps(env,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
with output_path.open('x',encoding='utf-8') as out:
index=0
for thinking in (False,True):
for case in corpus['cases']:
index+=1
torch.manual_seed(SEED);torch.cuda.manual_seed_all(SEED)
print(f"Starting {index}/32 {case['id']} thinking={thinking}",flush=True)
result=generate(case['prompt'],thinking,1536)
judgment=score(case,result['scoring_text'],thinking,result['truncated'])
row=dict(case_id=case['id'],thinking=thinking,**result,score=judgment)
out.write(json.dumps(row,ensure_ascii=False)+'\n');out.flush()
print(f"Finished {index}/32 {judgment['reason']} tokens={result['output_tokens']} seconds={result['seconds']:.1f}",flush=True)
print('All 32 measured generations saved; analysis and submission still required',flush=True)
if __name__=='__main__':
main()