Coverage for inference/parallel_inference.py: 100%

50 statements  

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

1"""Opt-in per-symbol multiprocessing for main.py::on_data()'s Pass 1 heavy 

2inference (baseline + experts + multitask + expert-multitask + sequence 

3model calls) - see main.py's phase_v2.inference_parallelism.enabled flag 

4(default off). 

5 

6Honest framing, not oversold: per-symbol inference is now fast (~4.8ms 

7mean per symbol, post the weight-caching/batching pass - see 

8development/Problems.md) precisely because the previous, much larger cost 

9(Python/NumPy per-call dispatch overhead, a Python loop inside 

10_conv1d_causal) got fixed WITHOUT multiprocessing. IPC/pickling overhead 

11for submitting work to and receiving results from a separate process may 

12easily exceed any parallel win at this point, for a universe this size 

13(~30 symbols). Shipped default-off; the real judge is a real `lean 

14backtest .` run (Windows' ProcessPoolExecutor uses the `spawn` start 

15method, which re-bootstraps a new interpreter per worker - untested 

16territory inside Lean's own embedded-Python runtime, which is not a 

17standard `python.exe` process tree main.py was ever designed to be 

18spawned from. main.py's own pool-creation code treats ANY failure here, 

19including a hang on first use, as a signal to permanently fall back to 

20the always-correct sequential path for the rest of the run.) 

21 

22Workers hold their OWN copy of every model export (loaded once via 

23ProcessPoolExecutor's `initializer`, not re-sent on every call - sending 

24model weights, now real NumPy arrays post the weight-caching pass, 

25through IPC on every single bar would defeat the whole purpose). Only 

26small per-symbol data (a flat feature vector, an optional sequence-window 

27history) crosses the process boundary per call. Never a bound method on 

28`self` (the QCAlgorithm instance holds Lean/.NET interop objects that are 

29almost certainly unpicklable) - this module has zero Lean/main.py 

30dependency, by design. 

31""" 

32 

33from __future__ import annotations 

34 

35from data_pipeline.bar_synthesis import pad_sequence_history 

36 

37# Populated once per worker process by init_worker() below - never sent 

38# across the process boundary again after that, and never touched by the 

39# main process itself. 

40_worker_model_exports: dict | None = None 

41 

42 

43def windows_parallelism_slowdown_warning(platform: str) -> str | None: 

44 """Returns the Windows-specific inference-parallelism slowdown warning 

45 for main.py to self.Debug() once, right after the pool starts 

46 successfully - None on every other platform, since this has only ever 

47 been measured on Windows (development/Problems.md #65: Windows' 

48 spawn-based ProcessPoolExecutor measured dramatically slower than 

49 sequential - single-digit-ms sequential bars vs. multi-second, in one 

50 run five-figure-ms, pooled bars). Never claims anything about 

51 Linux/fork, which this project has never measured.""" 

52 if platform != "win32": 

53 return None 

54 return ( 

55 "phase_v2.inference_parallelism.enabled is active on Windows - " 

56 "development/Problems.md #65 measured this ProcessPoolExecutor " 

57 "pool as dramatically slower than sequential on Windows' spawn " 

58 "start method (single-digit-ms sequential bars vs. multi-second, " 

59 "in one run five-figure-ms, pooled bars). Not measured on " 

60 "Linux/fork. Consider setting phase_v2.inference_parallelism.enabled " 

61 "back to false unless your own measurement shows otherwise." 

62 ) 

63 

64 

65def init_worker(model_exports: dict) -> None: 

66 """ProcessPoolExecutor `initializer` - runs once when each worker 

67 process starts, storing this run's model exports (baseline, experts, 

68 multitask, expert-multitask, sequence, plus their precomputed 

69 BatchedLayerStackCache/BatchedMultitaskLayerStackCache instances) in 

70 that worker's own global state.""" 

71 global _worker_model_exports 

72 _worker_model_exports = model_exports 

73 

74 

75def _padded_sequence(history: list[list[float]], window_size: int) -> list[list[float]]: 

76 """V5.5.0 (V5.4.5 audit note): delegates to the one shared implementation, 

77 data_pipeline/bar_synthesis.py::pad_sequence_history(), instead of keeping 

78 a third copy that could drift. That helper raises on an empty history 

79 (#123); this off-by-default pool path has always returned [] for it (the 

80 caller then runs no sequence model), so that case stays guarded here.""" 

81 if not history: 

82 return [] 

83 return pad_sequence_history(history, window_size) 

84 

85 

86def run_symbol_inference( 

87 inputs: list[float], 

88 sequence_history: list[list[float]] | None, 

89 sequence_window_size: int, 

90) -> dict: 

91 """The actual per-symbol work submitted to the pool - reads this 

92 worker's own _worker_model_exports (set once by init_worker()) and 

93 runs the exact same 5-call cluster main.py::on_data()'s Pass 1 always 

94 ran inline: baseline, sequence (if history given), experts (batched 

95 when possible), multitask, expert-multitask (batched when possible). 

96 

97 Returns a plain dict of plain values - always picklable back to the 

98 main process, matching the same graceful-degradation contract 

99 (missing/failed pieces -> None/empty, never a raised exception 

100 propagating out) every other inference call site in this codebase 

101 already has.""" 

102 from inference.exported_model import ( 

103 run_exported_model, 

104 run_exported_models_batched, 

105 run_exported_multitask_model, 

106 run_exported_multitask_models_batched, 

107 run_exported_sequence_multitask_model, 

108 ) 

109 

110 exports = _worker_model_exports or {} 

111 expert_names: list[str] = exports.get("expert_names", []) 

112 

113 result: dict = { 

114 "baseline_probability": None, 

115 "sequence_result": None, 

116 "expert_probabilities": dict.fromkeys(expert_names), 

117 "multitask_result": None, 

118 "expert_multitask_magnitudes": dict.fromkeys(expert_names), 

119 "expert_multitask_volatilities": dict.fromkeys(expert_names), 

120 } 

121 

122 baseline = exports.get("baseline") 

123 if baseline: 

124 try: 

125 result["baseline_probability"] = run_exported_model(baseline, inputs) 

126 except Exception: 

127 pass 

128 

129 sequence = exports.get("sequence") 

130 if sequence and sequence_history: 

131 try: 

132 padded = _padded_sequence(sequence_history, sequence_window_size) 

133 result["sequence_result"] = run_exported_sequence_multitask_model(sequence, padded) 

134 except Exception: 

135 pass 

136 

137 expert_exports = exports.get("experts", {}) 

138 expert_list = [expert_exports.get(name) for name in expert_names] 

139 if any(expert_list): 

140 expert_results = run_exported_models_batched(expert_list, inputs, stack_cache=exports.get("expert_stack_cache")) 

141 result["expert_probabilities"] = dict(zip(expert_names, expert_results, strict=False)) 

142 

143 multitask = exports.get("multitask") 

144 if multitask: 

145 try: 

146 result["multitask_result"] = run_exported_multitask_model(multitask, inputs) 

147 except Exception: 

148 pass 

149 

150 expert_multitask_exports = exports.get("expert_multitask", {}) 

151 expert_multitask_list = [expert_multitask_exports.get(name) for name in expert_names] 

152 if any(expert_multitask_list): 

153 emt_results = run_exported_multitask_models_batched( 

154 expert_multitask_list, inputs, stack_cache=exports.get("expert_multitask_stack_cache") 

155 ) 

156 for name, one_result in zip(expert_names, emt_results, strict=False): 

157 result["expert_multitask_magnitudes"][name] = one_result.get("magnitude") if one_result else None 

158 result["expert_multitask_volatilities"][name] = one_result.get("volatility") if one_result else None 

159 

160 return result