Skip to content

Commit c3bf59f

Browse files
committed
Overlap the complete LLM CPU grid with GPU serving on original cores
1 parent fdbc632 commit c3bf59f

8 files changed

Lines changed: 264 additions & 2 deletions
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"schema_version": 1,
3+
"registered_before_llm_cpu_main_measurements": "2026-11-10",
4+
"execution": "The complete 220-request LLM CPU main grid runs after all 12818 SGNS main requests finish, while GPU serving may continue on disjoint CPU cores. Use the original per-model CPU affinity, query inputs, cache budgets, three repeats and fresh worker implementation. The original LLM dispatcher later consumes these outputs without rerunning them.",
5+
"reference_gate": "Both CPU reference coordinators additionally wait for the complete LLM CPU overlap grid. The original dispatcher still orders SGNS references before LLM references, so reference phases cannot overlap on their original physical cores.",
6+
"claim": "Shared-host CPU measurements with unchanged numerical work and explicit source/output hashes. Earlier execution reduces scheduling wait; it does not create an exclusive-host latency claim."
7+
}

‎benchmarks/memory_application_reference_concurrency_addendum_v1.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"registered_before_any_reference_measurement": "2026-11-10",
44
"authorization": "Maintainer explicitly requested using both machines at full available concurrency.",
55
"scope": "All 1728 SGNS and 84 LLM primary-budget reference requests. Preserve every family, selected winner, raw/native baseline, original query trace and repetition count.",
6-
"execution": "Eight concurrent fixed-core lanes on the original CPU measurement host. Each lane executes one fresh single-thread process at a time, on the same assigned physical core as that model's main measurements. Start only after that phase's complete main grid and all local GPU work finish.",
6+
"execution": "Eight concurrent fixed-core lanes on the original CPU measurement host. Each lane executes one fresh single-thread process at a time, on the same assigned physical core as that model's main measurements. Start only after that phase's complete main grid and all local GPU work finish. When the CPU phase-overlap plan is present, the complete LLM CPU main grid must also finish before either reference phase, preventing concurrent use of the same core.",
77
"provenance": "Record reference execution mode, worker count, source hash, plan hash, core affinity, local GPU gate and all original output hashes. Legacy serial-reference paths identify the request group, not exclusive execution. Preserve legacy dispatch controllers separately.",
88
"claim": "Independent complete reference queries under concurrent fixed-core load. Memory bandwidth remains shared. These references do not support a host-exclusive CPU latency claim; report their actual execution mode in figures and summaries."
99
}

‎tests/test_cpu_phase_overlap.py‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
"""Advance complete CPU work without changing hardware or overlapping core users."""
2+
import json
3+
from pathlib import Path
4+
import socket
5+
import tempfile
6+
import threading
7+
from types import SimpleNamespace
8+
import unittest
9+
from unittest.mock import patch
10+
11+
from tools.cpu_phase_overlap import ready, run, validate
12+
from tools.parallel_cpu_serving import digest
13+
14+
15+
class CpuPhaseOverlapTests(unittest.TestCase):
16+
def fixture(self, root):
17+
requests=[]
18+
lanes={str(i):{'cpus':[i]} for i in range(6)}
19+
for i in range(6):
20+
job=root/f'm{i}.json';job.write_text('{}')
21+
for cache in (0,1048576):
22+
requests.append({'model':f'm{i}','name':'native','job':str(job),
23+
'mode':'codec','batch':1,'cache':cache})
24+
hardware={'lanes':lanes,'model_lanes':{'retime-llm-cpu':{f'm{i}':str(i) for i in range(6)}}}
25+
original=root/'cpu-serving-parallel-plan.json';original.write_text(json.dumps(hardware))
26+
plan={'measurement_host':socket.gethostname(),'original_cpu_plan_sha256':digest(original),
27+
'requests':requests,'upstream':str(root)}
28+
(root/'cpu-phase-overlap-plan.json').write_text(json.dumps(plan))
29+
(root/'retime-long').mkdir()
30+
(root/'retime-long/report.json').write_text(json.dumps({'status':'running-serial-references',
31+
'requests':[{}],'complete':[{}]}))
32+
return requests,original
33+
34+
def test_complete_six_lane_cohort_uses_original_fresh_worker_arguments(self):
35+
with tempfile.TemporaryDirectory() as temp:
36+
root=Path(temp);requests,original=self.fixture(root)
37+
barrier=threading.Barrier(6);seen=set();lock=threading.Lock()
38+
def execute(command,stdout,stderr,env):
39+
arg=lambda key:command[command.index('--'+key)+1]
40+
lane=arg('lane')
41+
with lock:first=lane not in seen;seen.add(lane)
42+
if first:barrier.wait(timeout=5)
43+
self.assertEqual(arg('cpu-list'),lane)
44+
self.assertEqual(arg('plan'),str(original))
45+
self.assertEqual(arg('requests'),'32')
46+
self.assertEqual(env['CUDA_VISIBLE_DEVICES'],'')
47+
output=Path(arg('output'));self.assertFalse(output.exists())
48+
output.write_text(json.dumps({'status':'complete','job_sha256':digest(arg('job')),
49+
'cpu_parallel_plan_sha256':digest(original),'cpu_lane':lane,'cpu_affinity':[int(lane)],
50+
'measurement_cohort':'parallel-shared-host'}))
51+
return SimpleNamespace(returncode=0)
52+
with patch('tools.finalize_memory_application.llm_requests',return_value=requests), \
53+
patch('tools.tree_node_quality.environment',return_value={'fixture':True}), \
54+
patch('tools.cpu_phase_overlap.subprocess.run',side_effect=execute):run(root)
55+
report=json.loads((root/'cpu-phase-overlap/report.json').read_text())
56+
self.assertEqual(report['status'],'complete');self.assertEqual(len(report['complete']),12)
57+
self.assertEqual(seen,set(map(str,range(6))))
58+
self.assertEqual({json.dumps(v['request'],sort_keys=True) for v in report['complete']},
59+
{json.dumps(v,sort_keys=True) for v in requests})
60+
self.assertFalse((root/'retime-llm-cpu/report.json').exists())
61+
62+
def test_gate_requires_all_sgns_main_outputs_and_rejects_failure(self):
63+
with tempfile.TemporaryDirectory() as temp:
64+
root=Path(temp);self.assertFalse(ready(root));self.fixture(root)
65+
self.assertTrue(ready(root))
66+
target=root/'retime-long/report.json'
67+
target.write_text(json.dumps({'status':'running','requests':[{},{}],'complete':[{}]}))
68+
self.assertFalse(ready(root))
69+
target.write_text(json.dumps({'status':'failed'}))
70+
with self.assertRaises(RuntimeError):ready(root)
71+
72+
def test_changed_plan_or_incomplete_requests_are_rejected(self):
73+
with tempfile.TemporaryDirectory() as temp:
74+
root=Path(temp);requests,original=self.fixture(root)
75+
with patch('tools.finalize_memory_application.llm_requests',return_value=requests):validate(root)
76+
with patch('tools.finalize_memory_application.llm_requests',return_value=requests[:-1]):
77+
with self.assertRaises(ValueError):validate(root)
78+
original.write_text('{}')
79+
with self.assertRaises(ValueError):validate(root)
80+
81+
82+
if __name__=='__main__':unittest.main()

‎tools/cpu_parallel_references.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,16 @@ def run(root,phase):
6161
out=folder/'report.json';write(out,report);deadline=time.monotonic()+24*3600
6262
primary=root/phase/'report.json';marker=root/hardware['local_gpu_finished_marker']
6363
while True:
64+
overlap_ready=True
65+
if (root/'cpu-phase-overlap-plan.json').exists():
66+
overlap=root/'cpu-phase-overlap/report.json'
67+
execution=load(overlap) if overlap.exists() else {'status':'not-started'}
68+
if execution['status']=='failed':raise RuntimeError('LLM CPU overlap failed; reference cores remain reserved')
69+
overlap_ready=execution['status']=='complete'
6470
if primary.exists():
6571
timer=load(primary)
6672
if timer['status']=='failed':raise RuntimeError('Main CPU grid failed; references remain blocked')
67-
if len(timer['complete'])==len(timer['requests']) and marker.exists():
73+
if len(timer['complete'])==len(timer['requests']) and marker.exists() and overlap_ready:
6874
gate=load(marker)
6975
if gate['status']!='complete' or gate['measurement_host']!=socket.gethostname():raise ValueError('Wrong reference GPU gate')
7076
break

‎tools/cpu_phase_overlap.py‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
"""Precompute the unchanged LLM CPU grid while local GPU serving continues.
2+
3+
Use the original six physical-core lanes only after the SGNS main grid drains.
4+
The original dispatcher later consumes these fresh outputs without repeating
5+
queries. Reference coordinators wait for this cohort, preventing core overlap.
6+
"""
7+
import argparse
8+
from concurrent.futures import ThreadPoolExecutor
9+
import json
10+
import os
11+
from pathlib import Path
12+
import socket
13+
import subprocess
14+
import sys
15+
import threading
16+
import time
17+
18+
from .parallel_cpu_serving import check_sample, digest, load
19+
20+
21+
def validate(root):
22+
from .finalize_memory_application import llm_requests
23+
path = root / 'cpu-phase-overlap-plan.json'
24+
plan = load(path)
25+
original = root / 'cpu-serving-parallel-plan.json'
26+
hardware = load(original)
27+
if plan['measurement_host'] != socket.gethostname():
28+
raise ValueError('Wrong CPU overlap host')
29+
if plan['original_cpu_plan_sha256'] != digest(original):
30+
raise ValueError('Original CPU affinity plan changed')
31+
requests = [r for r in llm_requests(root / 'llm-frontier', root / 'independent-controls')
32+
if r['mode'] == 'codec' and r['batch'] == 1]
33+
if requests != plan['requests']:
34+
raise ValueError('The complete original LLM CPU request grid changed')
35+
return plan, hardware, original
36+
37+
38+
def ready(root):
39+
path = root / 'retime-long/report.json'
40+
if not path.exists():
41+
return False
42+
report = load(path)
43+
if report['status'] == 'failed':
44+
raise RuntimeError('SGNS main grid failed; overlap remains blocked')
45+
return bool(report['requests']) and len(report['complete']) == len(report['requests'])
46+
47+
48+
def run(root):
49+
from .tree_node_quality import environment, write
50+
plan, hardware, original = validate(root)
51+
folder = root / 'cpu-phase-overlap'
52+
folder.mkdir(exist_ok=True)
53+
target = folder / 'report.json'
54+
if target.exists():
55+
raise ValueError('Preserve previous overlap controller before restarting')
56+
report = {'status': 'waiting-for-complete-sgns-main-grid',
57+
'environment': environment(), 'plan_sha256': digest(root / 'cpu-phase-overlap-plan.json'),
58+
'phase_source_sha256': digest(__file__), 'requests': plan['requests'],
59+
'complete': [], 'failures': [], 'workers': 6}
60+
write(target, report)
61+
deadline = time.monotonic() + 24 * 3600
62+
while not ready(root):
63+
if time.monotonic() >= deadline:
64+
raise TimeoutError('CPU main-grid wait expired; existing workers preserved')
65+
time.sleep(5)
66+
report.update(status='running', started=time.time())
67+
write(target, report)
68+
phase = 'retime-llm-cpu'
69+
outputs = root / phase
70+
outputs.mkdir(exist_ok=True)
71+
lock = threading.Lock()
72+
failed = threading.Event()
73+
74+
def lane_work(lane):
75+
cpus = hardware['lanes'][lane]['cpus']
76+
for index, request in enumerate(plan['requests']):
77+
if failed.is_set():
78+
return
79+
if hardware['model_lanes'][phase][request['model']] != lane:
80+
continue
81+
output = outputs / f'{index:05d}.json'
82+
try:
83+
if output.exists():
84+
raise ValueError('Fresh overlap output required; another scheduler is active')
85+
command = ['taskset', '--cpu-list', ','.join(map(str, cpus)), sys.executable,
86+
'-m', 'tools.parallel_cpu_serving', 'worker', '--phase', phase,
87+
'--job', request['job'], '--output', str(output), '--plan', str(original),
88+
'--lane', lane, '--cohort', 'parallel-shared-host', '--cache', str(request['cache']),
89+
'--requests', '32', '--upstream', plan['upstream']]
90+
log = folder / f'{index:05d}.{time.time_ns()}.log'
91+
with log.open('w') as stream:
92+
result = subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT,
93+
env=dict(os.environ, CUDA_VISIBLE_DEVICES='', OMP_NUM_THREADS='1',
94+
OPENBLAS_NUM_THREADS='1', MKL_NUM_THREADS='1'))
95+
if result.returncode:
96+
raise RuntimeError('LLM CPU overlap worker failed: ' + str(log))
97+
check_sample(load(output), request, plan['original_cpu_plan_sha256'], lane, cpus,
98+
'parallel-shared-host')
99+
with lock:
100+
report['complete'].append({'request': request, 'output': str(output), 'sha256': digest(output)})
101+
write(target, report)
102+
print({'llm_cpu_complete': len(report['complete']), 'total': len(plan['requests'])}, flush=True)
103+
except BaseException as error:
104+
failed.set()
105+
with lock:
106+
report['failures'].append({'request': request, 'error': repr(error)})
107+
raise
108+
109+
try:
110+
lanes = sorted(set(hardware['model_lanes'][phase].values()))
111+
with ThreadPoolExecutor(max_workers=6) as pool:
112+
list(pool.map(lane_work, lanes))
113+
if len(report['complete']) != len(plan['requests']):
114+
raise ValueError('Complete unchanged LLM CPU cohort required')
115+
report.update(status='complete', finished=time.time())
116+
except BaseException as error:
117+
report.update(status='failed', error=repr(error))
118+
raise
119+
finally:
120+
write(target, report)
121+
122+
123+
def main():
124+
parser = argparse.ArgumentParser(description=__doc__)
125+
parser.add_argument('--root', type=Path, required=True)
126+
args = parser.parse_args()
127+
try:
128+
run(args.root)
129+
except BaseException as error:
130+
path = args.root / 'cpu-phase-overlap/report.json'
131+
if path.exists():
132+
value = load(path)
133+
value.update(status='failed', error=repr(error))
134+
from .tree_node_quality import write
135+
write(path, value)
136+
raise
137+
138+
139+
if __name__ == '__main__':
140+
main()

‎tools/finish_memory_application.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ def source_commits(root, sources):
7575
"""Inventory actual source versions, including prior exact/hash controls."""
7676
files = {root / 'quality-ready.json'}
7777
files.update(root.glob('*.json'))
78+
if (root/'cpu-phase-overlap/report.json').exists():files.add(root/'cpu-phase-overlap/report.json')
7879
files.update(root.glob('cache-preflight-*/report.json'))
7980
files.update(root / family / 'report.json' for family in ('long-row-audit', 'llm-row-audit'))
8081
for family in ('long-frontier', 'llm-frontier'):

‎tools/publish_memory_application.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,14 @@ def main():
413413
if (args.root/'cpu-parallel-reference-plan.json').exists():
414414
archive.take(args.root/'cpu-parallel-reference-plan.json','cpu-parallel-reference-plan.json')
415415
archive.take(Path('benchmarks/memory_application_reference_concurrency_addendum_v1.json'),'reference-concurrency-addendum.json')
416+
if (args.root/'cpu-phase-overlap-plan.json').exists():
417+
plan=load(args.root/'cpu-phase-overlap-plan.json')
418+
timer=load(args.root/'cpu-phase-overlap/report.json')
419+
if timer['status']!='complete' or timer['requests']!=plan['requests'] or timer['failures']:
420+
raise ValueError('Complete unchanged LLM CPU overlap required')
421+
archive.take(args.root/'cpu-phase-overlap-plan.json','cpu-phase-overlap-plan.json')
422+
archive.take(args.root/'cpu-phase-overlap/report.json','diagnostics/cpu-phase-overlap-controller.json')
423+
archive.take(Path('benchmarks/memory_application_cpu_overlap_addendum_v1.json'),'cpu-phase-overlap-addendum.json')
416424
long_evidence(args, archive)
417425
llm_evidence(args, archive)
418426
runtimes(args, archive)

‎tools/verify_memory_application.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,23 @@ def verify_cpu_schedule(root, controller, frozen, records, phase, base, inventor
171171
logical.update(cpus); physical.update(cores)
172172
originals = {json.dumps(r['request'], sort_keys=True): r for r in records}
173173
assert len(originals) == len(controller['requests']) == len(controller['complete'])
174+
overlap=root/'cpu-phase-overlap-plan.json'
175+
overlap_finished=None
176+
if overlap.exists():
177+
execution=load(root/'diagnostics/cpu-phase-overlap-controller.json');overlap_plan=load(overlap)
178+
assert execution['status']=='complete' and execution['failures']==[] and execution['workers']==6
179+
assert execution['plan_sha256']==private['cpu-phase-overlap-plan.json']
180+
assert overlap_plan['original_cpu_plan_sha256']==private['cpu-serving-parallel-plan.json']
181+
files=inventory[execution['environment']['commit']]['files']
182+
assert execution['phase_source_sha256']==files['tools/cpu_phase_overlap.py']['original_sha256']
183+
assert execution['started']<=execution['finished']
184+
overlap_finished=execution['finished']
185+
if phase=='retime-llm-cpu':
186+
assert overlap_plan['requests']==execution['requests']==controller['requests']
187+
precalculated={json.dumps(v['request'],sort_keys=True):v for v in execution['complete']}
188+
assert len(precalculated)==len(execution['complete'])==len(originals)
189+
assert set(precalculated)==set(originals)
190+
for key,item in precalculated.items():assert item['sha256']==originals[key]['private_sha256']
174191
names = {}
175192
for model in frozen['models']:
176193
selected = set()
@@ -199,6 +216,7 @@ def verify_cpu_schedule(root, controller, frozen, records, phase, base, inventor
199216
assert report['measurement_host']==plan['measurement_host']==marker['measurement_host']
200217
assert report['local_gpu_gate_sha256']==private['local-gpu-finished.json']
201218
assert report['sample_started']>=marker['finished']
219+
if overlap_finished is not None:assert report['sample_started']>=overlap_finished
202220
if phase == 'retime-long':
203221
long_timing(report, load(folder / 'metadata.json'))
204222
else:

0 commit comments

Comments
 (0)