Coverage for src/python/ensembl/vep/bench/baseline.py: 98%

100 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-18 14:41 +0000

1# See the NOTICE file distributed with this work for additional information 

2# regarding copyright ownership. 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14"""Benchmark results on disk, and comparing a run against an earlier one. 

15 

16A number without its context is not comparable, so a results file carries what produced it: the 

17corpus spec and its parameter hash, the git revision and whether the tree was dirty, the machine, 

18and the timing policy. A comparison across two different corpora is refused rather than reported. 

19 

20Timings regress past a threshold. The declared cost per overlap is deterministic, so any change in 

21it is a change in behaviour -- reported as such, and not held to a threshold. 

22""" 

23 

24from __future__ import annotations 

25 

26import json 

27import os 

28import platform 

29import subprocess 

30from datetime import datetime, timezone 

31from pathlib import Path 

32 

33import attrs 

34from attrs import field, frozen 

35 

36__all__ = [ 

37 "COST_METRIC", 

38 "FORMAT_VERSION", 

39 "TIMING_METRICS", 

40 "BenchResults", 

41 "Comparison", 

42 "Regression", 

43 "RunInfo", 

44 "compare_results", 

45 "git_state", 

46 "machine_info", 

47 "utc_timestamp", 

48] 

49 

50FORMAT_VERSION = 1 

51TIMING_METRICS = ("ms_per_1k", "batch_ms_per_1k", "ns_per_case") 

52"""The metrics a regression is judged on. Lower is better for all of them.""" 

53COST_METRIC = "cost_per_context" 

54 

55 

56def machine_info() -> dict[str, object]: 

57 """Return what about this machine could explain a different timing.""" 

58 return { 

59 "system": platform.system(), 

60 "release": platform.release(), 

61 "machine": platform.machine(), 

62 "processor": platform.processor(), 

63 "python": platform.python_version(), 

64 "cpus": os.cpu_count(), 

65 } 

66 

67 

68def git_state() -> dict[str, object]: 

69 """Return the git revision and whether the tree is dirty, or Nones outside a repository.""" 

70 try: 

71 revision = subprocess.run( 

72 ["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True, timeout=10 

73 ).stdout.strip() 

74 status = subprocess.run( 

75 ["git", "status", "--porcelain"], capture_output=True, text=True, check=True, timeout=10 

76 ).stdout 

77 except (OSError, subprocess.SubprocessError): 

78 return {"revision": None, "dirty": None} 

79 return {"revision": revision, "dirty": bool(status.strip())} 

80 

81 

82def utc_timestamp() -> str: 

83 """Return the current UTC time, to the second.""" 

84 return datetime.now(timezone.utc).isoformat(timespec="seconds") 

85 

86 

87@frozen(kw_only=True, auto_attribs=True) 

88class RunInfo: 

89 """What produced a set of results. 

90 

91 Attributes: 

92 verb (str): The bench verb that ran. 

93 corpus (dict[str, object]): The corpus spec. 

94 corpus_parameters (str): The spec's parameter hash. 

95 git (dict[str, object]): Revision and dirtiness. 

96 machine (dict[str, object]): See machine_info. 

97 timestamp (str): When the run finished. 

98 repeats (int): Timed samples per measurement. 

99 warmup (int): Untimed passes per measurement. 

100 """ 

101 

102 verb: str 

103 corpus: dict[str, object] = field(factory=dict) 

104 corpus_parameters: str = field(default="") 

105 git: dict[str, object] = field(factory=dict) 

106 machine: dict[str, object] = field(factory=dict) 

107 timestamp: str = field(default="") 

108 repeats: int = field(default=0) 

109 warmup: int = field(default=0) 

110 

111 

112@frozen(kw_only=True, auto_attribs=True) 

113class BenchResults: 

114 """A run's rows and what produced them. 

115 

116 Attributes: 

117 info (RunInfo): The run's context. 

118 rows (tuple[dict[str, object], ...]): One row per measurement, each with ``corpus`` and 

119 ``configuration`` keys plus its metrics. 

120 """ 

121 

122 info: RunInfo 

123 rows: tuple[dict[str, object], ...] = field(default=()) 

124 

125 def to_json(self) -> str: 

126 """Return the results as indented JSON.""" 

127 payload = {"format_version": FORMAT_VERSION, "info": attrs.asdict(self.info), "rows": list(self.rows)} 

128 return json.dumps(payload, indent=1, sort_keys=True) + "\n" 

129 

130 @classmethod 

131 def from_json(cls, text: str) -> BenchResults: 

132 """Read results back. 

133 

134 Raises: 

135 ValueError: If the file was written in a different format version. 

136 """ 

137 payload = json.loads(text) 

138 if payload.get("format_version") != FORMAT_VERSION: 

139 raise ValueError(f"results format {payload.get('format_version')!r} is not {FORMAT_VERSION}") 

140 return cls(info=RunInfo(**payload["info"]), rows=tuple(payload["rows"])) 

141 

142 def write(self, path: Path) -> None: 

143 """Write the results, creating the directory if needed.""" 

144 path.parent.mkdir(parents=True, exist_ok=True) 

145 path.write_text(self.to_json(), encoding="utf-8") 

146 

147 @classmethod 

148 def load(cls, path: Path) -> BenchResults: 

149 """Read results from a file.""" 

150 return cls.from_json(path.read_text(encoding="utf-8")) 

151 

152 

153@frozen(kw_only=True, auto_attribs=True) 

154class Regression: 

155 """A timing that got slower than the threshold allows. 

156 

157 Attributes: 

158 corpus (str): The corpus. 

159 configuration (str): The configuration. 

160 metric (str): The metric that regressed. 

161 baseline (float): Its value in the baseline. 

162 current (float): Its value now. 

163 """ 

164 

165 corpus: str 

166 configuration: str 

167 metric: str 

168 baseline: float 

169 current: float 

170 

171 @property 

172 def change(self) -> float: 

173 """Return the fractional change, where 0.1 is ten percent slower.""" 

174 return self.current / self.baseline - 1 

175 

176 def line(self) -> str: 

177 """Return the regression as one readable line.""" 

178 return ( 

179 f"{self.corpus} / {self.configuration}: {self.metric} {self.baseline:.3f} -> {self.current:.3f} " 

180 f"({self.change:+.1%})" 

181 ) 

182 

183 

184@frozen(kw_only=True, auto_attribs=True) 

185class Comparison: 

186 """A run compared against a baseline. 

187 

188 Attributes: 

189 corpus_changed (bool): The two were run over different corpora, so nothing else is meaningful. 

190 regressions (tuple[Regression, ...]): Timings past the threshold. 

191 cost_changes (tuple[str, ...]): Configurations whose declared cost per overlap moved. 

192 unmatched (tuple[str, ...]): Rows of the current run the baseline has no counterpart for. 

193 """ 

194 

195 corpus_changed: bool = field(default=False) 

196 regressions: tuple[Regression, ...] = field(default=()) 

197 cost_changes: tuple[str, ...] = field(default=()) 

198 unmatched: tuple[str, ...] = field(default=()) 

199 

200 @property 

201 def ok(self) -> bool: 

202 """Return whether the run is comparable and no timing regressed.""" 

203 return not (self.corpus_changed or self.regressions) 

204 

205 

206def _as_float(value: object) -> float | None: 

207 """Return a metric as a float, or None if it is not a number.""" 

208 if isinstance(value, bool) or not isinstance(value, (int, float)): 

209 return None 

210 return float(value) 

211 

212 

213def compare_results(baseline: BenchResults, current: BenchResults, *, threshold: float) -> Comparison: 

214 """Compare a run against a baseline, row by row. 

215 

216 Args: 

217 baseline (BenchResults): The earlier run. 

218 current (BenchResults): This run. 

219 threshold (float): Fractional slowdown that counts as a regression. 

220 

221 Returns: 

222 Comparison: What changed. 

223 """ 

224 if baseline.info.corpus_parameters != current.info.corpus_parameters: 

225 return Comparison(corpus_changed=True) 

226 

227 earlier = {(str(row["corpus"]), str(row["configuration"])): row for row in baseline.rows} 

228 regressions: list[Regression] = [] 

229 cost_changes: list[str] = [] 

230 unmatched: list[str] = [] 

231 for row in current.rows: 

232 key = (str(row["corpus"]), str(row["configuration"])) 

233 previous = earlier.get(key) 

234 if previous is None: 

235 unmatched.append(f"{key[0]} / {key[1]}") 

236 continue 

237 for metric in TIMING_METRICS: 

238 before, after = _as_float(previous.get(metric)), _as_float(row.get(metric)) 

239 if before is not None and after is not None and before > 0 and after > before * (1 + threshold): 

240 regressions.append( 

241 Regression( 

242 corpus=key[0], configuration=key[1], metric=metric, baseline=before, current=after 

243 ) 

244 ) 

245 before_cost, after_cost = _as_float(previous.get(COST_METRIC)), _as_float(row.get(COST_METRIC)) 

246 if before_cost is not None and after_cost is not None and before_cost != after_cost: 

247 cost_changes.append(f"{key[0]} / {key[1]}: cost/ctx {before_cost:.3f} -> {after_cost:.3f}") 

248 return Comparison( 

249 regressions=tuple(regressions), cost_changes=tuple(cost_changes), unmatched=tuple(unmatched) 

250 )