|
| 1 | +"""Parallelize full matched model cohorts by fixed official prompt slices.""" |
| 2 | +import argparse |
| 3 | +from concurrent.futures import ThreadPoolExecutor |
| 4 | +import copy |
| 5 | +import json |
| 6 | +import os |
| 7 | +from pathlib import Path |
| 8 | +import socket |
| 9 | +import statistics |
| 10 | +import sys |
| 11 | +import threading |
| 12 | +import time |
| 13 | + |
| 14 | +from .gpu_spare_lanes import command, digest, load, check_result |
| 15 | +from .gpu_job_retry import run_gpu_job |
| 16 | + |
| 17 | + |
| 18 | +def targets(plan): |
| 19 | + groups=plan['groups'];seen=set();cpus=set() |
| 20 | + if plan['schema_version']!=1:raise ValueError('Registered prompt-shard schema required') |
| 21 | + for group in groups.values(): |
| 22 | + if len(group)!=4:raise ValueError('Four fixed prompt shards required') |
| 23 | + for i,lane in enumerate(group): |
| 24 | + if lane['slice']!=[8*i,8] or lane['gpu'] in seen or cpus.intersection(lane['cpus']): |
| 25 | + raise ValueError('Disjoint GPU/core assignments and complete fixed slices required') |
| 26 | + seen.add(lane['gpu']);cpus.update(lane['cpus']) |
| 27 | + return [(i,r) for i,r in enumerate(plan['requests']) if r['model'] in groups] |
| 28 | + |
| 29 | + |
| 30 | +def aggregate(request, records, group, *, request_count=32): |
| 31 | + if len(records)!=len(group):raise ValueError('Every registered shard required') |
| 32 | + ordered=sorted(records,key=lambda r:r['report']['request_slice'][0]);reports=[v['report'] for v in ordered] |
| 33 | + cursor=0 |
| 34 | + for record,lane in zip(ordered,group): |
| 35 | + value=record['report'];start,count=value['request_slice'] |
| 36 | + if start!=cursor or count<1 or len(value['requests'])!=count: |
| 37 | + raise ValueError('Overlapping, missing or shortened prompt slices') |
| 38 | + check_result(value,request,lane['gpu'],lane['cpus']) |
| 39 | + if len(value['samples'])!=count*3:raise ValueError('Three repeats per original prompt required') |
| 40 | + cursor+=count |
| 41 | + if cursor!=request_count:raise ValueError('Full original prompt count required') |
| 42 | + fields=('job_sha256','mode','batch_size','decode_steps','cache_bytes','complete_serving_bytes','base_model_bytes', |
| 43 | + 'source_row_bytes','decoded_row_sha256','phase_source_sha256','codec_adapter_source_sha256','cached_decode_source_sha256') |
| 44 | + for value in reports[1:]: |
| 45 | + if any(value.get(k)!=reports[0].get(k) for k in fields):raise ValueError('Shard model, bytes or runtime changed') |
| 46 | + result=copy.deepcopy(reports[0]);result.pop('gpu_before');result.pop('gpu_samples') |
| 47 | + result.update(measurement_mode='matched-prompt-shards',shards=ordered,request_slice=[0,request_count], |
| 48 | + selected_gpu_selector='matched-prompt-shards',cpu_affinity=[], |
| 49 | + requests=[v for r in reports for v in r['requests']],samples=[v for r in reports for v in r['samples']], |
| 50 | + unique_prompt_count=len({p for r in reports for v in r['requests'] for p in v['prompt_hashes']}), |
| 51 | + open_seconds=max(r['open_seconds'] for r in reports), |
| 52 | + aggregation_contract='Identical fixed prompt-to-GPU assignment for every method; per-request latency, not summed multi-GPU throughput') |
| 53 | + prefill=[v['prefill_ms'] for v in result['samples']];decode=[d for v in result['samples'] for d in v['decode_ms']] |
| 54 | + def percentile(values,p): |
| 55 | + values=sorted(values);at=(len(values)-1)*p;lo=int(at);hi=min(lo+1,len(values)-1) |
| 56 | + return values[lo]+(at-lo)*(values[hi]-values[lo]) |
| 57 | + result.update(prefill_p50_ms=statistics.median(prefill),prefill_p95_ms=percentile(prefill,.95), |
| 58 | + decode_p50_ms=statistics.median(decode),decode_p95_ms=percentile(decode,.95), |
| 59 | + decode_tokens_per_second=request['batch']*1000/statistics.mean(decode)) |
| 60 | + return result |
| 61 | + |
| 62 | + |
| 63 | +def route_pending_shard(args): |
| 64 | + plan_path=args.output.parent.parent/'gpu-prompt-shard-plan.json' |
| 65 | + if not plan_path.exists():return False |
| 66 | + plan=load(plan_path) |
| 67 | + if str(args.output.parent)!=plan['canonical_directory']:return False |
| 68 | + request=plan['requests'][int(args.output.stem)] |
| 69 | + if request['model'] not in plan['groups']:return False |
| 70 | + if (str(args.job),args.mode,args.cache_bytes,args.batch_size,args.requests,args.repeat,args.warmup,args.decode_steps)!=( |
| 71 | + request['job'],request['mode'],request['cache'],request['batch'],32,3,1,16): |
| 72 | + raise ValueError('Frozen original request or budget changed') |
| 73 | + if request['mode']=='independent' and str(args.control_run)!=request['control_run']:raise ValueError('Independent control changed') |
| 74 | + from .tree_node_quality import write |
| 75 | + target=plan_path.parent/'gpu-prompt-shards/outputs'/args.output.name;deadline=time.monotonic()+24*3600 |
| 76 | + while not target.exists(): |
| 77 | + controller=plan_path.parent/'gpu-prompt-shards/report.json' |
| 78 | + if controller.exists() and load(controller)['status']=='failed':raise RuntimeError('Prompt shard controller failed; diagnostics retained') |
| 79 | + if time.monotonic()>deadline:raise TimeoutError('Prompt-shard wait expired; workers retained') |
| 80 | + time.sleep(5) |
| 81 | + value=load(target) |
| 82 | + if value['status']!='passed' or value['job_sha256']!=digest(args.job):raise ValueError('Complete matched shards required') |
| 83 | + cpus=sorted(os.sched_getaffinity(0)) |
| 84 | + if cpus!=plan['original_cpu_affinity'][request['model']]:raise ValueError('Original route core assignment changed') |
| 85 | + receipt={'status':'passed','measurement_purpose':'prompt-shard-routing-receipt-only','job_sha256':digest(args.job), |
| 86 | + 'cpu_affinity':cpus,'request':request,'prompt_shard_plan_sha256':digest(plan_path), |
| 87 | + 'shard_measurement_output':str(target),'shard_measurement_sha256':digest(target)} |
| 88 | + if args.output.exists(): |
| 89 | + if load(args.output)!=receipt:raise ValueError('Completed original evidence must never be overwritten') |
| 90 | + else:write(args.output,receipt) |
| 91 | + return True |
| 92 | + |
| 93 | + |
| 94 | +def run(plan_path): |
| 95 | + from .tree_node_quality import environment,write |
| 96 | + plan=load(plan_path);expected=targets(plan) |
| 97 | + if socket.gethostname()!=plan['measurement_host']:raise ValueError('Wrong physical measurement host') |
| 98 | + root=plan_path.parent;folder=root/'gpu-prompt-shards';(folder/'outputs').mkdir(parents=True,exist_ok=True) |
| 99 | + report={'status':'running','environment':environment(),'measurement_host':socket.gethostname(), |
| 100 | + 'requests':[r for _,r in expected],'complete':[],'preflights':[],'failures':[], |
| 101 | + 'plan_sha256':digest(plan_path),'phase_source_sha256':digest(__file__),'workers':8,'workers_per_gpu':1} |
| 102 | + lock=threading.Lock();path=folder/'report.json';write(path,report) |
| 103 | + def measure(request,output,lane,preflight=False): |
| 104 | + cmd=command(request,output,plan['upstream'],repeat=1 if preflight else 3,warmup=0 if preflight else 1) |
| 105 | + cmd+=['--request-offset',str(lane['slice'][0]),'--request-count',str(2 if preflight else lane['slice'][1])] |
| 106 | + cmd=['taskset','--cpu-list',','.join(map(str,lane['cpus'])),*cmd] |
| 107 | + env=dict(os.environ,CUDA_VISIBLE_DEVICES=str(lane['gpu']),OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1') |
| 108 | + output.parent.mkdir(parents=True,exist_ok=True) |
| 109 | + result=run_gpu_job(cmd,env=env,output=output,log=output.with_suffix('.'+str(time.time_ns())+'.log')) |
| 110 | + if result.returncode:raise RuntimeError('Prompt shard worker failed: '+str(output)) |
| 111 | + value=load(output);check_result(value,request,lane['gpu'],lane['cpus']) |
| 112 | + if value['measurement_host']!=plan['measurement_host']:raise ValueError('A shard ran on a different host') |
| 113 | + return {'report':value,'output':str(output),'sha256':digest(output)} |
| 114 | + def lane_work(item): |
| 115 | + model,lane=item;gpu=lane['gpu'] |
| 116 | + source=next(r for _,r in expected if r['model']==model and r['name']=='source-gpu' and r['batch']==8) |
| 117 | + native=next(r for _,r in expected if r['model']==model and r['name']=='native-none-fp32' and r['batch']==8 and r['cache']==0) |
| 118 | + values=[measure(r,folder/'preflights'/f'{model}-gpu{gpu}-{name}.json',lane,True) for r,name in ((source,'source'),(native,'native'))] |
| 119 | + for a,b in zip(values[0]['report']['requests'],values[1]['report']['requests']): |
| 120 | + if any(a[k]!=b[k] for k in ('input_ids_sha256','cached_logit_hashes','generated_ids_sha256')):raise ValueError('New card source/native preflight changed bytes') |
| 121 | + with lock:report['preflights'].append({'model':model,'gpu':gpu,'records':values});write(path,report) |
| 122 | + for index,request in expected: |
| 123 | + if request['model']!=model:continue |
| 124 | + measure(request,folder/'shards'/f'{index:05d}-gpu{gpu}.json',lane) |
| 125 | + with lock: |
| 126 | + outputs=[folder/'shards'/f'{index:05d}-gpu{other["gpu"]}.json' for other in plan['groups'][model]] |
| 127 | + final=folder/'outputs'/f'{index:05d}.json' |
| 128 | + if all(p.exists() and load(p).get('status')=='passed' for p in outputs) and not final.exists(): |
| 129 | + records=[{'report':load(p),'output':str(p),'sha256':digest(p)} for p in outputs] |
| 130 | + value=aggregate(request,records,plan['groups'][model]);value['prompt_shard_plan_sha256']=digest(plan_path) |
| 131 | + value['aggregation_source_sha256']=digest(__file__);write(final,value) |
| 132 | + if final.exists() and not any(v['request']==request for v in report['complete']): |
| 133 | + report['complete'].append({'request':request,'output':str(final),'sha256':digest(final)}) |
| 134 | + write(path,report);print({'complete':len(report['complete']),'expected':len(expected)},flush=True) |
| 135 | + try: |
| 136 | + with ThreadPoolExecutor(max_workers=8) as pool:list(pool.map(lane_work,[(m,lane) for m,group in plan['groups'].items() for lane in group])) |
| 137 | + if len(report['complete'])!=len(expected):raise ValueError('Full prompt-sharded cohort required') |
| 138 | + report.update(status='complete',finished=time.time());write(path,report) |
| 139 | + write(root/plan['gpu_finished_marker'],{'status':'complete','measurement_host':socket.gethostname(), |
| 140 | + 'finished':report['finished'],'controller_sha256':digest(path)}) |
| 141 | + except BaseException as error:report['status']='failed';report['failures'].append({'error':repr(error)});raise |
| 142 | + finally:write(path,report) |
| 143 | + |
| 144 | + |
| 145 | +def publish_cohort(root,timer,values,archive): |
| 146 | + plan_path=root/'gpu-prompt-shard-plan.json' |
| 147 | + if not plan_path.exists():return timer,values |
| 148 | + from .publish_memory_application import check_controller |
| 149 | + plan=load(plan_path);expected=targets(plan) |
| 150 | + if plan['requests']!=timer['requests']:raise ValueError('Prompt sharding changed original schedule') |
| 151 | + controller,results=check_controller(root/'gpu-prompt-shards',[r for _,r in expected]) |
| 152 | + if controller['plan_sha256']!=digest(plan_path):raise ValueError('Prompt shard plan changed') |
| 153 | + archive.take(plan_path,'gpu-prompt-shard-plan.json') |
| 154 | + archive.take(Path('benchmarks/memory_application_multi_host_addendum_v1.json'),'multi-host-addendum.json') |
| 155 | + archive.take(root/'gpu-prompt-shards/report.json','llm/prompt-shard-controller.json') |
| 156 | + archive.put('llm/pre-sharded-gpu-controller.json',timer) |
| 157 | + archive.put('llm/pre-sharded-gpu-records.json.gz',[{'request':v['request'],'private_sha256':v['sha256'], |
| 158 | + 'report':values[json.dumps(v['request'],sort_keys=True)]} for v in timer['complete'] if v['request']['model'] in plan['groups']]) |
| 159 | + replacement={json.dumps(v['request'],sort_keys=True):v for v in controller['complete']} |
| 160 | + complete=[replacement.get(json.dumps(v['request'],sort_keys=True),v) for v in timer['complete']] |
| 161 | + final={**timer,'complete':complete,'workers':16,'prompt_shard_plan_sha256':digest(plan_path), |
| 162 | + 'prompt_shard_groups':plan['groups'],'prompt_shard_host':plan['measurement_host'], |
| 163 | + 'cohort_contract':'Complete model cohorts with identical per-prompt hardware assignments for every method'} |
| 164 | + archive.put('llm/retiming-gpu-controller.json',final) |
| 165 | + return final,{**values,**results} |
| 166 | + |
| 167 | + |
| 168 | +def main(): |
| 169 | + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--plan',type=Path,required=True) |
| 170 | + run(parser.parse_args().plan) |
| 171 | + |
| 172 | + |
| 173 | +if __name__=='__main__':main() |
0 commit comments