"""Publication-style vLLM long diagnostic. Trusted steering callbacks only.""" import os import json from pathlib import Path import modal app=modal.App('modelclinic-vllm-long-v1');vol=modal.Volume.from_name(os.environ.get("MODELCLINIC_MODAL_VOLUME", "modelclinic-cache"),create_if_missing=False) image=(modal.Image.debian_slim(python_version='3.11').pip_install('vllm==0.33.0','transformers==5.20.2','math-verify==0.9.0') .env({'VLLM_USE_FLASHINFER_SAMPLER':'0','VLLM_ALLOW_INSECURE_SERIALIZATION':'1'}) .add_local_file('code/src/long_protocol.py','/root/project/long_protocol.py') .add_local_file('experiments/evaluation/long_diagnostic_5.jsonl','/root/project/questions.jsonl') .add_local_file('results/pilot_001/calibration.json','/root/project/calibration.json')) BASE='2fc06364715b967f1860aea9cf38778875588b17';EDIT='d1671a178705bcab7644806d23c535517f35723b' CONDITIONS=['base','edited','constant'];MAX_TIME=1800;MAX_NEW=32768 def install_hooks(model,specs): import torch found=[] for layer,direction,coef in specs: matches=[(n,m) for n,m in model.named_modules() if n.endswith(f'layers.{layer}.mlp.down_proj')] if len(matches)!=1:raise RuntimeError(f'Expected exactly one down projection for layer {layer}: {len(matches)}') name,module=matches[0];v=torch.tensor(direction,device=module.weight.device,dtype=module.weight.dtype);state={'calls':0} def hook(_m,_a,out,_v=v,_coef=coef,_state=state): y=out[0] if isinstance(out,tuple) else out;_state['calls']+=1;y=y+_v.to(dtype=y.dtype)*_coef return (y,*out[1:]) if isinstance(out,tuple) else y module._modelclinic_hook=module.register_forward_hook(hook);module._modelclinic_state=state;found.append(name) return found def hook_stats(model): return {n:getattr(m,'_modelclinic_state',None) for n,m in model.named_modules() if hasattr(m,'_modelclinic_state')} @app.function(image=image,gpu='A10',volumes={'/cache':vol},cpu=2,memory=16384,timeout=2100,scaledown_window=2,max_containers=3) def run_one(index:int,condition:str): import sys,time,os,hashlib,traceback,torch,vllm from vllm import LLM,SamplingParams from transformers import AutoTokenizer from collections import Counter sys.path.insert(0,'/root/project');from long_protocol import build_prompt,strict_grade vol.reload();assert 0<=index<5 and condition in CONDITIONS questions=[json.loads(s) for s in Path('/root/project/questions.jsonl').read_text(encoding='utf8').splitlines() if s.strip()];q=questions[index];cal=json.loads(Path('/root/project/calibration.json').read_text());root=Path('/cache/modelclinic/vllm_long_v1');root.mkdir(parents=True,exist_ok=True);out=root/f"{q['source_row']}_{condition}.json";partial=root/f"{q['source_row']}_{condition}.partial.json" if out.exists(): e=json.loads(out.read_text());return {'reused':True,'path':str(out),'row':q['source_row'],'condition':condition,'error':e.get('error'),'finish':e.get('finish_reason')} if partial.exists():return {'blocked_partial':True,'path':str(partial),'row':q['source_row'],'condition':condition} root_start=time.monotonic();path=f'/cache/modelclinic/{"edited-"+EDIT if condition=="edited" else "base-"+BASE}';tok=AutoTokenizer.from_pretrained(path,local_files_only=True) llm=LLM(model=path,dtype='bfloat16',gpu_memory_utilization=.85,max_model_len=34816,enforce_eager=True,seed=0,trust_remote_code=False) installed=None if condition=='constant': specs=[(i,v,float(c)) for i,v,c in zip((15,19),cal['directions'],cal['coefficients'])];installed=llm.apply_model(lambda m:install_hooks(m,specs));assert installed and all(len(x)==2 for x in installed) prompt=build_prompt(q['problem']);formatted=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True,enable_thinking=True);params=SamplingParams(n=1,temperature=.6,top_p=.95,top_k=20,presence_penalty=1.5,max_tokens=MAX_NEW,seed=0) engine=llm.llm_engine;reqid=f'{q["source_row"]}-{condition}';engine.add_request(reqid,formatted,params);latest=[];last=0;finish=None;error=None;generated_start=time.monotonic();last_output=None try: while engine.has_unfinished_requests(): if time.monotonic()-generated_start>=MAX_TIME:engine.abort_request([reqid]);finish='wall_time';break for output in engine.step(): if output.request_id!=reqid or not output.outputs:continue o=output.outputs[0];token_ids=list(o.token_ids) if len(token_ids)=1024: last=len(latest);tmp=partial.with_suffix('.tmp');tmp.write_text(json.dumps({'condition':condition,'source_row':q['source_row'],'token_ids':latest,'seconds':time.monotonic()-generated_start}));os.replace(tmp,partial);vol.commit();print('checkpoint',condition,q['source_row'],len(latest),flush=True) except Exception as e:error=f'{type(e).__name__}: {str(e)[:600]}';print(traceback.format_exc(),flush=True) elapsed=time.monotonic()-generated_start;response=tok.decode(latest,skip_special_tokens=False);stats=llm.apply_model(hook_stats) if condition=='constant' and not error else None if condition=='constant' and not error and (not stats or any(any(v['calls']==0 for v in worker.values()) for worker in stats)):error='Steering hook recorded zero calls';finish='error' eight=Counter(tuple(latest[i:i+8]) for i in range(max(0,len(latest)-7)));rec={'source_row':q['source_row'],'id':q['unique_id'],'question':q['problem'],'reference_answer':q['answer'],'condition':condition,'base_revision':BASE,'edited_revision':EDIT,'model_revision':EDIT if condition=='edited' else BASE,'precision':'bfloat16','backend':'vLLM 0.33.0 eager, native top-k/top-p sampler, one sample per problem','prompt':prompt,'formatted_prompt':formatted,'thinking':True,'settings':{'temperature':.6,'top_p':.95,'top_k':20,'presence_penalty':1.5,'max_new_tokens':MAX_NEW,'wall_limit_seconds':MAX_TIME,'seed':0},'generated_token_ids':latest,'response':response,'score':strict_grade(response,q['answer']),'reasoning_closed':'' in response,'tokens':len(latest),'finish_reason':'error' if error else finish,'stop_reason':getattr(last_output,'stop_reason',None),'eos_id_in_output':bool(latest and latest[-1]==248044),'truncated':finish in ('length','wall_time'),'loop_heuristic':{'max_eightgram_frequency':max(eight.values(),default=0),'definition':'max repeated 8-token frequency, not a validated loop classifier'},'elapsed_seconds':elapsed,'total_function_seconds':time.monotonic()-root_start,'gpu':torch.cuda.get_device_name(),'vllm_version':vllm.__version__,'hook_modules':installed,'hook_stats':stats,'calibration_sha256':hashlib.sha256(Path('/root/project/calibration.json').read_bytes()).hexdigest(),'error':error} tmp=out.with_suffix('.tmp');tmp.write_text(json.dumps(rec,ensure_ascii=False));os.replace(tmp,out) if partial.exists():partial.unlink() vol.commit();print('saved',q['source_row'],condition,'tokens',len(latest),'finish',rec['finish_reason'],'seconds',round(elapsed,1),flush=True) return {'path':str(out),'row':q['source_row'],'condition':condition,'tokens':len(latest),'finish':rec['finish_reason'],'seconds':elapsed,'score':rec['score'],'gpu':rec['gpu'],'error':error} @app.local_entrypoint() def main(stage:str='trial'): if stage=='trial':pairs=[(0,'base')] elif stage=='full':pairs=[(i,c) for i in range(5) for c in CONDITIONS] else:raise ValueError('stage must be trial or full') for start in range(0,len(pairs),3): failed=[] for r in run_one.starmap(pairs[start:start+3],order_outputs=False,return_exceptions=True): if isinstance(r,BaseException):failed.append(str(r));print('failure',str(r),flush=True);continue print(json.dumps(r),flush=True) if r.get('error') or r.get('blocked_partial'):failed.append(str(r)) if failed:raise RuntimeError('Failed/partial generation; inspect before retry: '+str(failed))