Skip to content

Commit cabfe13

Browse files
committed
Shard complete GPU cohorts across a second host and overlap the full CPU frontier
1 parent a09afd3 commit cabfe13

7 files changed

Lines changed: 399 additions & 8 deletions
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"schema_version": 1,
3+
"registered_before_new_host_measurements": "2026-11-10",
4+
"gpu": "Two complete model/seed cohorts use eight additional GPUs. Each model uses four fixed contiguous eight-request slices of the unchanged 32 official requests. Every method uses identical prompt-to-device/core assignments. Each prompt keeps its original batch, first pass, warmup, three repetitions and 16 decode steps. Aggregate per-request latency, never sum GPU throughput. Retain earlier single-device samples as diagnostics.",
5+
"preflight": "Every new GPU runs source/native byte-equality checks on two actual batch-8 requests from its registered slice before timing.",
6+
"cpu": "Eight disjoint physical cores on the new host execute full CPU query measurements concurrently with GPU work. These are shared-host measurements. Serial reference queries wait until all GPU work on that host completes. Original-host GPU timing may continue on a different physical machine.",
7+
"provenance": "Record actual host, GPU UUID, CPU topology, request slice, child report hashes and complete canonical coverage. Original quality grids, training exposures, frozen choices and request budgets remain unchanged."
8+
}

‎tests/test_gpu_prompt_shards.py‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
"""Prompt sharding retains every official request and matched hardware."""
2+
import copy
3+
import json
4+
from pathlib import Path
5+
import tempfile
6+
import unittest
7+
from unittest.mock import patch
8+
9+
from tools.gpu_prompt_shards import aggregate,targets,digest
10+
from tools.verify_memory_application import llm_timing
11+
12+
13+
def fixture(root):
14+
job=root/'job.json';job.write_text('{}')
15+
request={'job':str(job),'model':'m','mode':'codec','batch':8,'cache':0,'name':'native-none-fp32'}
16+
group=[{'gpu':i,'cpus':[i,i+128],'slice':[8*i,8]} for i in range(4)]
17+
records=[]
18+
for lane in group:
19+
start,count=lane['slice'];gpu=lane['gpu']
20+
queries=[{'prompt_hashes':[f'prompt-{i}-{j}' for j in range(8)],'batch_case_ids':list(range(8))} for i in range(start,start+count)]
21+
samples=[{'prefill_ms':float(i+1),'decode_ms':[float(i+2)]*16} for i in range(24)]
22+
report={'status':'passed','job_sha256':digest(job),'mode':'codec','batch_size':8,'cache_bytes':0,'decode_steps':16,
23+
'selected_gpu_selector':str(gpu),'cpu_affinity':lane['cpus'],'request_slice':lane['slice'],
24+
'requests':queries,'samples':samples,'unique_prompt_count':64,'open_seconds':1.,
25+
'gpu_before':{'compute_pids':[],'external_compute_pids':[],'utilization_percent':0},
26+
'gpu_samples':[{'compute_pids':[123],'external_compute_pids':[]}],
27+
'batch_contract':'Each batch uses distinct real official prompts',
28+
'prefill_p50_ms':12.5,'prefill_p95_ms':22.85,'decode_p50_ms':13.5,'decode_p95_ms':24.,
29+
'decode_tokens_per_second':8*1000/13.5}
30+
# The same per-request decode samples appear 16 times, so p95 uses
31+
# the repeated sample distribution rather than 24 scalar observations.
32+
report['decode_p95_ms']=24.
33+
records.append({'report':report,'sha256':'hash'})
34+
return request,group,records
35+
36+
37+
class PromptShardTests(unittest.TestCase):
38+
def test_all_256_prompts_and_96_samples_survive_and_metrics_are_recomputed(self):
39+
with tempfile.TemporaryDirectory() as temp:
40+
request,group,records=fixture(Path(temp));value=aggregate(request,records,group)
41+
self.assertEqual(value['unique_prompt_count'],256);self.assertEqual(len(value['requests']),32)
42+
self.assertEqual(len(value['samples']),96);self.assertEqual(value['selected_gpu_selector'],'matched-prompt-shards')
43+
self.assertNotIn('gpu_before',value)
44+
llm_timing(value,'gpu')
45+
46+
def test_missing_overlapping_or_shortened_slices_are_rejected(self):
47+
with tempfile.TemporaryDirectory() as temp:
48+
request,group,records=fixture(Path(temp))
49+
with self.assertRaisesRegex(ValueError,'Every'):aggregate(request,records[:3],group)
50+
altered=copy.deepcopy(records);altered[1]['report']['request_slice']=[4,8]
51+
with self.assertRaisesRegex(ValueError,'Overlapping'):aggregate(request,altered,group)
52+
altered=copy.deepcopy(records);altered[1]['report']['samples'].pop()
53+
with self.assertRaisesRegex(ValueError,'Three repeats'):aggregate(request,altered,group)
54+
55+
def test_same_prompt_slice_cannot_silently_switch_device_or_model_bytes(self):
56+
with tempfile.TemporaryDirectory() as temp:
57+
request,group,records=fixture(Path(temp));records[1]['report']['selected_gpu_selector']='3'
58+
with self.assertRaisesRegex(ValueError,'hardware'):aggregate(request,records,group)
59+
records[1]['report']['selected_gpu_selector']='1';records[1]['report']['decoded_row_sha256']='changed'
60+
with self.assertRaisesRegex(ValueError,'bytes'):aggregate(request,records,group)
61+
62+
def test_plan_requires_disjoint_cards_and_cpu_cores(self):
63+
with tempfile.TemporaryDirectory() as temp:
64+
request,group,_=fixture(Path(temp));plan={'schema_version':1,'groups':{'m':group},'requests':[request]}
65+
self.assertEqual(targets(plan),[(0,request)])
66+
group[1]['cpus']=[0]
67+
with self.assertRaisesRegex(ValueError,'Disjoint'):targets(plan)
68+
69+
70+
if __name__=='__main__':unittest.main()

‎tools/benchmark_llm_codec_serving.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from pathlib import Path
77
import subprocess
88
import time
9+
import socket
910

1011
import numpy as np
1112

@@ -163,6 +164,8 @@ def gpu_worker(args):
163164
'rss_before_open':memory(), 'requests':[], 'samples':[],
164165
'contract':'Actual complete prefill plus native decoder KV/recurrent cache; causal TinyEngram history, original IDs and unchanged nonrow weights',
165166
'rounding_contract':'Cache vs full-prefix differences are measured separately. Source and byte-exact codecs execute the same cached schedule.'}
167+
report['measurement_host'] = socket.gethostname()
168+
report['request_slice'] = [args.request_offset, args.request_count or args.requests]
166169
model = replay = staged = None
167170
def snapshot():
168171
value = gpu_snapshot(uuid, own_pid=monitor_pid); report['gpu_samples'].append(value)
@@ -188,6 +191,7 @@ def snapshot():
188191
cuda_after_open={'allocated':torch.cuda.memory_allocated(), 'reserved':torch.cuda.memory_reserved(),
189192
'peak_allocated':torch.cuda.max_memory_allocated()})
190193
requests = batches_for(common, 'test', args.requests, args.batch_size)
194+
requests = requests[args.request_offset:args.request_offset + (args.request_count or args.requests)]
191195
prefixes = [torch.tensor([row['ids'] for row in batch], dtype=torch.int64) for batch in requests]
192196
report['unique_prompt_count'] = len({tuple(row['ids']) for batch in requests for row in batch})
193197
continuations = []
@@ -274,15 +278,21 @@ def main():
274278
parser.add_argument('--warmup',type=int,default=1)
275279
parser.add_argument('--decode-steps',type=int,default=16)
276280
parser.add_argument('--batch-size',type=int,default=1)
281+
parser.add_argument('--request-offset',type=int,default=0)
282+
parser.add_argument('--request-count',type=int)
277283
parser.add_argument('--skip-spare-routing',action='store_true',
278284
help='Internal child for a registered spare-device cohort; keeps the actual GPU measurement unchanged')
279285
args=parser.parse_args()
280286
if args.phase == 'gpu' and not args.skip_spare_routing:
287+
from .gpu_prompt_shards import route_pending_shard
288+
if route_pending_shard(args): return
281289
from .gpu_spare_lanes import route_pending
282290
if route_pending(args): return
283291
if args.output.exists() or args.requests<1 or args.repeat<1 or args.warmup<0 or args.cache_bytes<0:
284292
parser.error('fresh output and valid positive budgets required')
285293
if args.mode == 'independent' and args.control_run is None: parser.error('independent mode requires a trained control run')
294+
if args.request_offset < 0 or (args.request_count is not None and (args.request_count < 1 or args.request_offset + args.request_count > args.requests)):
295+
parser.error('A request slice must fit the unchanged full request schedule')
286296
args.output.parent.mkdir(parents=True,exist_ok=True)
287297
if args.phase=='cpu':cpu_worker(args)
288298
else:gpu_worker(args)

‎tools/gpu_prompt_shards.py‎

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
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

Comments
 (0)