Coverage for scripts/profile_inference.py: 100%

228 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""cProfile + wall-clock harness for main.py's per-bar inference hot path 

2(inference/exported_model.py). 

3 

4No profiling harness existed anywhere in this repo before this - see 

5development/Problems.md for the full writeup. A real Lean backtest is 

6off the table for repeated profiling runs on this dev machine (a single 

7run takes over an hour), so this harness uses REAL exported model weights 

8already on disk under ml/ (not synthetic/random ones - the point is 

9realistic layer shapes and call volume, not realistic predictions) fed 

10synthetic-but-correctly-shaped input vectors, called in a loop sized to 

11approximate a real backtest's call volume (N_BARS * N_SYMBOLS calls to 

12each of baseline/experts/multitask/expert-multitask, matching 

13main.py::on_data()'s actual per-symbol-per-bar call pattern). 

14 

15Two things a first version of this harness got wrong, fixed here: 

16- Random input GENERATION used to happen INSIDE the profiled region, so 

17 cProfile measured the harness's own `random.uniform` overhead as if it 

18 were inference cost (~150s of an early 448s baseline was this, not 

19 inference - see development/Problems.md). All inputs are now 

20 pre-generated once, before profiling starts. 

21- No per-iteration wall-clock visibility existed - only cProfile's own 

22 aggregate totals, which include cProfile's own instrumentation overhead 

23 and say nothing about tail latency. Every iteration is now timed 

24 independently via time.perf_counter(), reported as p50/p95/p99/max/mean. 

25 

26Mirrors main.py's own load-time optimizations: every loaded export gets 

27convert_state_dict_arrays() applied once (matching main.py's model 

28loaders), and --batched additionally builds+uses the same 

29BatchedLayerStackCache/BatchedMultitaskLayerStackCache main.py builds once 

30in _ensure_ready() - so this harness's --batched numbers reflect the real 

31optimized production path, not just "batched but rebuilding stacks every 

32call." 

33 

34Usage: 

35 python scripts/profile_inference.py [--iterations N] [--sort cumulative] [--batched] [--symbols-per-bar N] [--parallel] [--pool-workers N] 

36 

37--batched also runs a separate, additive sequence-encoder symbol-batching 

38comparison (run_sequence_unbatched_workload() vs 

39run_sequence_batched_workload(), V4.9 Priority 1) - see their own 

40docstrings. This is a wall-clock-only comparison outside cProfile's 

41profiled region, reported as its own section; it never changes the 

42primary tail-latency numbers above, which always time the sequence step 

43unbatched (matching run_workload()'s own per-symbol-bar call pattern). 

44 

45--parallel (V4.9 Priority 6) runs a further additive section: a real 

46ProcessPoolExecutor benchmark of inference/parallel_inference.py's 

47run_symbol_inference() (phase_v2.inference_parallelism) against an 

48identical sequential baseline calling the exact same function, answering 

49that module's own long-standing, never-measured IPC/pickling break-even 

50warning. See run_parallel_workload()/run_parallel_baseline_workload(). 

51Degrades to a reported "FAILED" line (never crashes the whole run) on any 

52pool creation/spawn/submit failure, matching main.py's own 

53permanent-fallback-to-sequential philosophy for this same failure mode. 

54 

55Writes a pstats dump (plus the tail-latency report) to 

56scripts/profile_inference_output.txt (overwritten each run) and prints 

57both to stdout. 

58""" 

59 

60from __future__ import annotations 

61 

62import argparse 

63import cProfile 

64import gc 

65import json 

66import pstats 

67import random 

68import sys 

69import time 

70from concurrent.futures import ProcessPoolExecutor 

71from pathlib import Path 

72 

73ROOT_DIR = Path(__file__).resolve().parent.parent 

74sys.path.insert(0, str(ROOT_DIR)) 

75 

76from inference import ( # noqa: E402 

77 convert_state_dict_arrays, 

78 init_worker, 

79 run_exported_model, 

80 run_exported_multitask_model, 

81 run_exported_sequence_multitask_model, 

82 run_symbol_inference, 

83) 

84 

85try: 

86 from inference import ( 

87 build_models_batched_cache, 

88 build_multitask_models_batched_cache, 

89 run_exported_models_batched, 

90 run_exported_multitask_models_batched, 

91 run_exported_sequence_multitask_model_batched, 

92 ) 

93except ImportError: 

94 run_exported_models_batched = None 

95 run_exported_multitask_models_batched = None 

96 build_models_batched_cache = None 

97 build_multitask_models_batched_cache = None 

98 run_exported_sequence_multitask_model_batched = None 

99 

100EXPERT_NAMES = ["bullish", "bearish", "sideways", "volatility"] 

101OUTPUT_PATH = Path(__file__).resolve().parent / "profile_inference_output.txt" 

102 

103 

104def _load_json(path: Path) -> dict | None: 

105 if not path.exists(): 

106 return None 

107 with path.open("r", encoding="utf-8") as f: 

108 return json.load(f) 

109 

110 

111def _random_inputs(width: int, rng: random.Random) -> list[float]: 

112 return [rng.uniform(-2.0, 2.0) for _ in range(width)] 

113 

114 

115def load_real_exports() -> dict: 

116 """Loads every real model export this repo has on disk under ml/ - 

117 never synthetic/fake weights, so profiled call cost reflects real 

118 layer shapes/counts, not a toy stand-in. Applies 

119 convert_state_dict_arrays() to each loaded export, matching 

120 main.py's own model loaders - this harness's numbers should reflect 

121 the real, already-optimized load-time behavior, not the pre-caching 

122 state.""" 

123 baseline = _load_json(ROOT_DIR / "ml" / "model_weights.json") 

124 multitask = _load_json(ROOT_DIR / "ml" / "multitask_model.json") 

125 sequence = _load_json(ROOT_DIR / "ml" / "sequence_model.json") 

126 experts = { 

127 name: _load_json(ROOT_DIR / "ml" / "expert_models" / name / "model_weights.json") for name in EXPERT_NAMES 

128 } 

129 expert_multitask = { 

130 name: _load_json(ROOT_DIR / "ml" / "expert_models" / name / "multitask_model.json") for name in EXPERT_NAMES 

131 } 

132 missing = [ 

133 label 

134 for label, value in [("baseline", baseline), ("multitask", multitask), ("sequence", sequence)] 

135 + [(f"expert:{n}", e) for n, e in experts.items()] 

136 + [(f"expert_multitask:{n}", e) for n, e in expert_multitask.items()] 

137 if value is None 

138 ] 

139 if missing: 

140 print(f"warning: missing real exports, profiling will skip them: {missing}", file=sys.stderr) 

141 

142 for export in [baseline, multitask, sequence, *experts.values(), *expert_multitask.values()]: 

143 if export is not None: 

144 convert_state_dict_arrays(export) 

145 

146 return { 

147 "baseline": baseline, 

148 "multitask": multitask, 

149 "sequence": sequence, 

150 "experts": experts, 

151 "expert_multitask": expert_multitask, 

152 } 

153 

154 

155def pregenerate_inputs( 

156 width: int, sequence_window: int, iterations: int, seed: int = 7 

157) -> list[tuple[list[float], list[list[float]]]]: 

158 """Pre-generates every iteration's (flat_inputs, sequence_inputs) pair 

159 OUTSIDE the profiled region, so profiling measures real inference cost 

160 only - not this harness's own random-number-generation overhead.""" 

161 rng = random.Random(seed) 

162 return [ 

163 (_random_inputs(width, rng), [_random_inputs(width, rng) for _ in range(sequence_window)]) 

164 for _ in range(iterations) 

165 ] 

166 

167 

168def percentile(sorted_values: list[float], p: float) -> float: 

169 """Nearest-rank percentile over an already-sorted list, p in [0, 100]. 

170 Returns 0.0 for an empty list rather than raising - a harness reporting 

171 helper should never itself crash a profiling run.""" 

172 if not sorted_values: 

173 return 0.0 

174 index = min(int(round(p / 100.0 * (len(sorted_values) - 1))), len(sorted_values) - 1) 

175 return sorted_values[index] 

176 

177 

178def summarize_durations(durations: list[float]) -> dict[str, float]: 

179 """p50/p95/p99/max/mean over a list of per-iteration wall-clock 

180 durations (seconds), reported in milliseconds - the first tail-latency 

181 visibility this repo has had for this hot path (cProfile's own 

182 aggregate stats say nothing about the worst-case bar).""" 

183 if not durations: 

184 return {"p50_ms": 0.0, "p95_ms": 0.0, "p99_ms": 0.0, "max_ms": 0.0, "mean_ms": 0.0} 

185 sorted_durations = sorted(durations) 

186 return { 

187 "p50_ms": percentile(sorted_durations, 50) * 1000, 

188 "p95_ms": percentile(sorted_durations, 95) * 1000, 

189 "p99_ms": percentile(sorted_durations, 99) * 1000, 

190 "max_ms": sorted_durations[-1] * 1000, 

191 "mean_ms": (sum(sorted_durations) / len(sorted_durations)) * 1000, 

192 } 

193 

194 

195def bucket_durations_by_iteration_index(durations: list[float], n_buckets: int = 10) -> list[dict[str, float]]: 

196 """Splits `durations` (already in call order, NOT re-sorted) into 

197 n_buckets contiguous, equal-sized-ish chunks and summarizes each via 

198 summarize_durations() - lets a caller see whether early iterations 

199 (bucket 0) are disproportionately slow (a warmup/cold-cache effect - 

200 e.g. OS page-fault-in of the weight arrays, CPU frequency-scaling 

201 ramp-up) versus tail spikes being roughly uniformly distributed 

202 across the whole run (pointing at GC pauses or OS scheduler 

203 preemption instead - neither of which correlates with call order). 

204 

205 Pure function: input is the exact same per-iteration duration list 

206 run_workload() already returns, in the exact order iterations ran - 

207 no new profiling region needed to use this. The last bucket absorbs 

208 any remainder when len(durations) doesn't divide evenly by 

209 n_buckets. Returns [] for an empty or non-positive n_buckets input.""" 

210 if not durations or n_buckets <= 0: 

211 return [] 

212 bucket_size = max(1, len(durations) // n_buckets) 

213 buckets = [durations[i : i + bucket_size] for i in range(0, len(durations), bucket_size)] 

214 return [summarize_durations(bucket) for bucket in buckets] 

215 

216 

217def run_workload( 

218 exports: dict, 

219 pregenerated_inputs: list[tuple[list[float], list[list[float]]]], 

220 use_batched: bool, 

221 stack_cache=None, 

222 multitask_stack_cache=None, 

223) -> list[float]: 

224 """Runs one full symbol-bar's worth of inference per pregenerated 

225 input tuple, matching main.py::on_data()'s per-symbol call pattern: 

226 1x baseline, 4x experts (or 1 batched call), 1x multitask, 4x 

227 expert-multitask (or 1 batched call), 1x sequence. Returns the 

228 wall-clock duration (seconds) of EACH iteration, timed independently 

229 of cProfile (whose own instrumentation adds overhead that would 

230 otherwise skew absolute numbers).""" 

231 baseline = exports["baseline"] 

232 multitask = exports["multitask"] 

233 sequence = exports["sequence"] 

234 expert_list = [exports["experts"][name] for name in EXPERT_NAMES if exports["experts"][name]] 

235 expert_multitask_list = [exports["expert_multitask"][name] for name in EXPERT_NAMES if exports["expert_multitask"][name]] 

236 

237 durations: list[float] = [] 

238 for flat_inputs, sequence_inputs in pregenerated_inputs: 

239 start = time.perf_counter() 

240 

241 if baseline: 

242 run_exported_model(baseline, flat_inputs) 

243 

244 if expert_list: 

245 if use_batched and run_exported_models_batched is not None: 

246 run_exported_models_batched(expert_list, flat_inputs, stack_cache=stack_cache) 

247 else: 

248 for export in expert_list: 

249 run_exported_model(export, flat_inputs) 

250 

251 if multitask: 

252 run_exported_multitask_model(multitask, flat_inputs) 

253 

254 if expert_multitask_list: 

255 if use_batched and run_exported_multitask_models_batched is not None: 

256 run_exported_multitask_models_batched( 

257 expert_multitask_list, flat_inputs, stack_cache=multitask_stack_cache 

258 ) 

259 else: 

260 for export in expert_multitask_list: 

261 run_exported_multitask_model(export, flat_inputs) 

262 

263 if sequence: 

264 run_exported_sequence_multitask_model(sequence, sequence_inputs) 

265 

266 durations.append(time.perf_counter() - start) 

267 return durations 

268 

269 

270def run_sequence_unbatched_workload(sequence_export: dict, pregenerated_sequences: list[list[list[float]]]) -> list[float]: 

271 """Isolated per-symbol sequence-model timing - the exact same 

272 run_exported_sequence_multitask_model() call run_workload() above 

273 already makes as part of a full symbol-bar's inference, pulled out on 

274 its own so it can be compared apples-to-apples against 

275 run_sequence_batched_workload() below without any other model's cost 

276 mixed in. One duration entry per symbol.""" 

277 durations: list[float] = [] 

278 for sequence in pregenerated_sequences: 

279 start = time.perf_counter() 

280 run_exported_sequence_multitask_model(sequence_export, sequence) 

281 durations.append(time.perf_counter() - start) 

282 return durations 

283 

284 

285def run_sequence_batched_workload( 

286 sequence_export: dict, pregenerated_sequences: list[list[list[float]]], symbols_per_bar: int 

287) -> list[float]: 

288 """Bar-grouped sibling of run_sequence_unbatched_workload() above - 

289 main.py's V4.9 symbol-batching (on_data()'s Phase 1b, 

290 inference/exported_model.py::run_exported_sequence_multitask_model_batched()) 

291 batches the sequence encoder across every PENDING SYMBOL IN ONE BAR, 

292 not across per-symbol model variants the way the expert/multitask 

293 --batched flag above does. Groups `pregenerated_sequences` (one entry 

294 per symbol) into chunks of `symbols_per_bar`, running ONE 

295 run_exported_sequence_multitask_model_batched() call per chunk. 

296 Returns one wall-clock duration PER BAR (per chunk), not per symbol, 

297 since that's the real unit of work main.py's own batching performs - 

298 divide by symbols_per_bar for a rough per-symbol-equivalent figure. 

299 Chunks with fewer than 2 symbols are skipped, matching main.py's own 

300 <2-present fallback threshold (not worth timing as "a batch" - the 

301 batched function itself would just degrade to the same individual 

302 calls run_sequence_unbatched_workload() already measures).""" 

303 durations: list[float] = [] 

304 for start_index in range(0, len(pregenerated_sequences), symbols_per_bar): 

305 chunk = pregenerated_sequences[start_index : start_index + symbols_per_bar] 

306 if len(chunk) < 2: 

307 continue 

308 start = time.perf_counter() 

309 run_exported_sequence_multitask_model_batched(sequence_export, chunk) 

310 durations.append(time.perf_counter() - start) 

311 return durations 

312 

313 

314def run_parallel_baseline_workload( 

315 exports_for_workers: dict, 

316 pregenerated_inputs: list[tuple[list[float], list[list[float]]]], 

317 sequence_window_size: int, 

318 symbols_per_bar: int, 

319) -> list[float]: 

320 """Sequential sibling of run_parallel_workload() below, calling the 

321 EXACT SAME inference/parallel_inference.py::run_symbol_inference() 

322 function in a plain per-symbol loop instead of through a process pool 

323 - isolates IPC/pickling overhead specifically (both paths run 

324 identical inference work per symbol; only the submission mechanism 

325 differs), rather than conflating it with some other per-symbol cost 

326 difference a less careful comparison might introduce. Groups into 

327 chunks of symbols_per_bar purely so its per-bar duration list lines up 

328 one-to-one with run_parallel_workload()'s own bar grouping.""" 

329 durations: list[float] = [] 

330 for start_index in range(0, len(pregenerated_inputs), symbols_per_bar): 

331 chunk = pregenerated_inputs[start_index : start_index + symbols_per_bar] 

332 start = time.perf_counter() 

333 for flat_inputs, sequence_inputs in chunk: 

334 run_symbol_inference(flat_inputs, sequence_inputs, sequence_window_size) 

335 durations.append(time.perf_counter() - start) 

336 return durations 

337 

338 

339def run_parallel_workload( 

340 exports_for_workers: dict, 

341 pregenerated_inputs: list[tuple[list[float], list[list[float]]]], 

342 sequence_window_size: int, 

343 symbols_per_bar: int, 

344 max_workers: int = 4, 

345) -> list[float] | None: 

346 """V4.9 Priority 6 - real ProcessPoolExecutor benchmark for 

347 phase_v2.inference_parallelism (inference/parallel_inference.py), 

348 answering that module's own long-standing, never-measured break-even 

349 warning: does IPC/pickling overhead for submitting 

350 run_symbol_inference() calls to a separate process exceed the win at 

351 this project's real per-symbol inference cost (~4.8ms mean, post the 

352 weight-caching/batching pass)? Groups pregenerated_inputs into chunks 

353 of symbols_per_bar (one ProcessPoolExecutor.submit() burst per chunk, 

354 matching main.py::on_data()'s own per-bar fan-out shape via 

355 init_worker()/run_symbol_inference() - see that module's docstring), 

356 timing wall-clock submit-through-gather for each chunk. 

357 

358 Returns None (never raises) on ANY pool creation/spawn/submit failure 

359 - matches main.py's own "any pool failure permanently falls back to 

360 the sequential path" philosophy exactly, including on this dev 

361 machine's own Windows 'spawn' start method, which re-bootstraps a full 

362 new interpreter per worker and has never been verified inside Lean's 

363 embedded-Python runtime (inference/parallel_inference.py's own module 

364 docstring).""" 

365 try: 

366 pool = ProcessPoolExecutor(max_workers=max_workers, initializer=init_worker, initargs=(exports_for_workers,)) 

367 except Exception: 

368 return None 

369 

370 durations: list[float] = [] 

371 try: 

372 for start_index in range(0, len(pregenerated_inputs), symbols_per_bar): 

373 chunk = pregenerated_inputs[start_index : start_index + symbols_per_bar] 

374 start = time.perf_counter() 

375 try: 

376 futures = [ 

377 pool.submit(run_symbol_inference, flat_inputs, sequence_inputs, sequence_window_size) 

378 for flat_inputs, sequence_inputs in chunk 

379 ] 

380 for future in futures: 

381 future.result(timeout=30) 

382 except Exception: 

383 return None 

384 durations.append(time.perf_counter() - start) 

385 finally: 

386 pool.shutdown(wait=True) 

387 return durations 

388 

389 

390def main() -> None: 

391 parser = argparse.ArgumentParser(description=__doc__) 

392 parser.add_argument("--iterations", type=int, default=10_000, help="Symbol-bar iterations to profile (default: 10000)") 

393 parser.add_argument("--sort", default="cumulative", help="pstats sort key (default: cumulative)") 

394 parser.add_argument( 

395 "--batched", action="store_true", 

396 help="Use run_exported_models_batched()/run_exported_multitask_models_batched() (plus their precomputed stack caches, matching main.py's real optimized path) instead of a per-expert loop", 

397 ) 

398 parser.add_argument( 

399 "--bucket-report", action="store_true", 

400 help="Print/write a 10-bucket breakdown of durations by iteration index (see bucket_durations_by_iteration_index()) - reveals whether the tail is a warmup effect (bucket 0 much slower) or spread evenly (points at GC/OS scheduling instead). Print-only, zero effect on the existing tail-latency/pstats numbers.", 

401 ) 

402 parser.add_argument( 

403 "--no-gc", action="store_true", 

404 help="Disable Python's garbage collector for the profiled region only (gc.disable()/gc.enable() around run_workload()) - isolates whether GC pauses are a material tail-latency contributor. Compare a --no-gc run against a normal run, back-to-back, to see if p99/max drop while p50 stays flat.", 

405 ) 

406 parser.add_argument( 

407 "--symbols-per-bar", type=int, default=74, 

408 help="V4.9 Priority 1/6: symbols-per-bar grouping for the sequence-encoder symbol-batching comparison (--batched, see run_sequence_batched_workload()) AND the --parallel IPC-overhead benchmark below (see run_parallel_workload()). Default 74 matches this repo's real universe size (development/architecture.md).", 

409 ) 

410 parser.add_argument( 

411 "--parallel", action="store_true", 

412 help="V4.9 Priority 6: run a real ProcessPoolExecutor benchmark of inference/parallel_inference.py's run_symbol_inference() (phase_v2.inference_parallelism) against an identical sequential baseline, answering that module's own never-measured IPC/pickling break-even warning. Independent of --batched (each stack_cache built here is reused if --batched is also passed).", 

413 ) 

414 parser.add_argument( 

415 "--pool-workers", type=int, default=4, 

416 help="Worker process count for --parallel's ProcessPoolExecutor (default: 4).", 

417 ) 

418 args = parser.parse_args() 

419 

420 exports = load_real_exports() 

421 

422 stack_cache = None 

423 multitask_stack_cache = None 

424 if args.batched and build_models_batched_cache is not None: 

425 stack_cache = build_models_batched_cache([exports["experts"].get(name) for name in EXPERT_NAMES]) 

426 multitask_stack_cache = build_multitask_models_batched_cache( 

427 [exports["expert_multitask"].get(name) for name in EXPERT_NAMES] 

428 ) 

429 

430 input_width = exports["baseline"]["export"]["architecture"][0]["in_features"] if exports["baseline"] else 85 

431 pregenerated_inputs = pregenerate_inputs(input_width, sequence_window=30, iterations=args.iterations) 

432 

433 profiler = cProfile.Profile() 

434 if args.no_gc: 

435 gc.disable() 

436 profiler.enable() 

437 try: 

438 durations = run_workload( 

439 exports, pregenerated_inputs, use_batched=args.batched, 

440 stack_cache=stack_cache, multitask_stack_cache=multitask_stack_cache, 

441 ) 

442 finally: 

443 profiler.disable() 

444 if args.no_gc: 

445 gc.enable() 

446 

447 tail_latency = summarize_durations(durations) 

448 tail_latency_lines = [f" {key}: {value:.4f} ms" for key, value in tail_latency.items()] 

449 

450 bucket_lines: list[str] = [] 

451 if args.bucket_report: 

452 buckets = bucket_durations_by_iteration_index(durations) 

453 bucket_lines.append("Duration by iteration-index bucket (0 = earliest iterations):") 

454 for index, bucket in enumerate(buckets): 

455 bucket_lines.append( 

456 f" bucket {index}: p50={bucket['p50_ms']:.4f}ms p99={bucket['p99_ms']:.4f}ms max={bucket['max_ms']:.4f}ms" 

457 ) 

458 

459 # V4.9 Priority 1 - sequence-encoder symbol-batching comparison, 

460 # additional/additive: run OUTSIDE cProfile's own profiled region 

461 # (this is a wall-clock-only comparison, not a hotspot breakdown) and 

462 # reported as its own separate section - never mixed into the primary 

463 # tail_latency numbers above, which stay exactly what they always 

464 # measured (a full symbol-bar's worth of every model, sequence always 

465 # unbatched, see run_workload()'s own sequence step). Only runs with 

466 # --batched and a real sequence export on disk. 

467 sequence_batch_lines: list[str] = [] 

468 if args.batched and exports["sequence"] and run_exported_sequence_multitask_model_batched is not None: 

469 sequence_only_inputs = [sequence_inputs for _, sequence_inputs in pregenerated_inputs] 

470 unbatched_sequence_durations = run_sequence_unbatched_workload(exports["sequence"], sequence_only_inputs) 

471 batched_sequence_durations = run_sequence_batched_workload( 

472 exports["sequence"], sequence_only_inputs, symbols_per_bar=args.symbols_per_bar 

473 ) 

474 unbatched_summary = summarize_durations(unbatched_sequence_durations) 

475 batched_summary = summarize_durations(batched_sequence_durations) 

476 per_symbol_equivalent_ms = ( 

477 batched_summary["mean_ms"] / args.symbols_per_bar if batched_summary["mean_ms"] else 0.0 

478 ) 

479 sequence_batch_lines.append( 

480 f"Sequence-encoder symbol-batching comparison (--symbols-per-bar {args.symbols_per_bar}, " 

481 f"isolated to JUST the sequence-model call, no other model's cost included):" 

482 ) 

483 sequence_batch_lines.append( 

484 f" unbatched, per symbol ({len(unbatched_sequence_durations)} symbols): " 

485 f"p50={unbatched_summary['p50_ms']:.4f}ms p99={unbatched_summary['p99_ms']:.4f}ms mean={unbatched_summary['mean_ms']:.4f}ms" 

486 ) 

487 sequence_batch_lines.append( 

488 f" batched, per BAR ({len(batched_sequence_durations)} bars): " 

489 f"p50={batched_summary['p50_ms']:.4f}ms p99={batched_summary['p99_ms']:.4f}ms mean={batched_summary['mean_ms']:.4f}ms" 

490 ) 

491 sequence_batch_lines.append( 

492 f" batched, per-symbol-equivalent (mean bar duration / symbols_per_bar): {per_symbol_equivalent_ms:.4f}ms " 

493 f"(vs {unbatched_summary['mean_ms']:.4f}ms unbatched mean)" 

494 ) 

495 

496 # V4.9 Priority 6 - real ProcessPoolExecutor IPC-overhead benchmark, 

497 # additional/additive, run OUTSIDE cProfile's own profiled region (a 

498 # ProcessPoolExecutor's own worker processes wouldn't be captured by 

499 # this process's cProfile instance anyway). Independent of --batched - 

500 # reuses stack_cache/multitask_stack_cache when --batched was ALSO 

501 # passed (a more realistic worker payload matching main.py's real 

502 # optimized path), but runs fine without them either way, same 

503 # graceful degrade run_exported_models_batched(stack_cache=None) 

504 # already has. 

505 parallel_lines: list[str] = [] 

506 if args.parallel: 

507 exports_for_workers = { 

508 "expert_names": EXPERT_NAMES, 

509 "baseline": exports["baseline"], 

510 "sequence": exports["sequence"], 

511 "experts": exports["experts"], 

512 "multitask": exports["multitask"], 

513 "expert_multitask": exports["expert_multitask"], 

514 "expert_stack_cache": stack_cache, 

515 "expert_multitask_stack_cache": multitask_stack_cache, 

516 } 

517 sequential_baseline_durations = run_parallel_baseline_workload( 

518 exports_for_workers, pregenerated_inputs, sequence_window_size=30, symbols_per_bar=args.symbols_per_bar, 

519 ) 

520 parallel_durations = run_parallel_workload( 

521 exports_for_workers, pregenerated_inputs, sequence_window_size=30, 

522 symbols_per_bar=args.symbols_per_bar, max_workers=args.pool_workers, 

523 ) 

524 baseline_summary = summarize_durations(sequential_baseline_durations) 

525 parallel_lines.append( 

526 f"ProcessPoolExecutor IPC-overhead comparison (--symbols-per-bar {args.symbols_per_bar}, " 

527 f"--pool-workers {args.pool_workers}, same run_symbol_inference() call both ways):" 

528 ) 

529 parallel_lines.append( 

530 f" sequential baseline, per BAR ({len(sequential_baseline_durations)} bars): " 

531 f"p50={baseline_summary['p50_ms']:.4f}ms p99={baseline_summary['p99_ms']:.4f}ms mean={baseline_summary['mean_ms']:.4f}ms" 

532 ) 

533 if parallel_durations is None: 

534 parallel_lines.append( 

535 " process-pool: FAILED (pool creation/spawn/submit error - see " 

536 "inference/parallel_inference.py's own module docstring on Windows 'spawn'-start-method risk; " 

537 "main.py's own pool would fall back to the sequential path permanently on this same failure)" 

538 ) 

539 else: 

540 pool_summary = summarize_durations(parallel_durations) 

541 verdict = "FASTER" if pool_summary["mean_ms"] < baseline_summary["mean_ms"] else "SLOWER (IPC overhead exceeds the win)" 

542 parallel_lines.append( 

543 f" process-pool, per BAR ({len(parallel_durations)} bars): " 

544 f"p50={pool_summary['p50_ms']:.4f}ms p99={pool_summary['p99_ms']:.4f}ms mean={pool_summary['mean_ms']:.4f}ms" 

545 ) 

546 parallel_lines.append(f" verdict at this symbols-per-bar/worker-count: pool is {verdict}") 

547 

548 header = f"--iterations {args.iterations} --batched {args.batched} --no-gc {args.no_gc}" 

549 stats = pstats.Stats(profiler).sort_stats(args.sort) 

550 with OUTPUT_PATH.open("w", encoding="utf-8") as f: 

551 f.write(header + "\n\n") 

552 f.write("Tail latency (wall-clock per iteration, independent of cProfile overhead):\n") 

553 f.write("\n".join(tail_latency_lines) + "\n\n") 

554 if bucket_lines: 

555 f.write("\n".join(bucket_lines) + "\n\n") 

556 if sequence_batch_lines: 

557 f.write("\n".join(sequence_batch_lines) + "\n\n") 

558 if parallel_lines: 

559 f.write("\n".join(parallel_lines) + "\n\n") 

560 stats_out = pstats.Stats(profiler, stream=f).sort_stats(args.sort) 

561 stats_out.print_stats(40) 

562 

563 print(header) 

564 print("Tail latency (wall-clock per iteration, independent of cProfile overhead):") 

565 print("\n".join(tail_latency_lines)) 

566 if bucket_lines: 

567 print() 

568 print("\n".join(bucket_lines)) 

569 if sequence_batch_lines: 

570 print() 

571 print("\n".join(sequence_batch_lines)) 

572 if parallel_lines: 

573 print() 

574 print("\n".join(parallel_lines)) 

575 print() 

576 stats.print_stats(25) 

577 print(f"\nFull pstats + tail-latency dump written to {OUTPUT_PATH}") 

578 

579 

580if __name__ == "__main__": 

581 main()