Coverage for src/python/ensembl/vep/runner/bench/endtoend.py: 88%
131 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« 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"""End-to-end command-line benchmarks over exported corpora."""
16from __future__ import annotations
18import logging
19import os
20import subprocess
21import tempfile
22from pathlib import Path
23from typing import ClassVar
25from ensembl.vep.bench.baseline import BenchResults
26from ensembl.vep.bench.endtoend import (
27 EndToEndRow,
28 output_mismatches,
29 run_command,
30 run_once,
31 summarise,
32 time_runs,
33)
34from ensembl.vep.bench.harness import REFERENCE_STRATEGY, consequence_strategies
35from ensembl.vep.bench.suites import Configuration, build_configurations
36from ensembl.vep.bench.workspace import MissingTool, Workspace
37from ensembl.vep.config import Config
38from ensembl.vep.corpus.registry import build_corpus
39from ensembl.vep.corpus.spec import CorpusSpec
40from ensembl.vep.render.table import TableFormat, render_table
41from ensembl.vep.runner.base import ExitCode
42from ensembl.vep.runner.bench import common
43from ensembl.vep.runner.registry import register_runner
45__all__ = ["Runner"]
47logger = logging.getLogger(__name__)
49HEADERS = ("Configuration", "processes", "s", "ms/1k variants", "variants/s", "peak RSS MB", "vs reference")
50"""Columns of the results table. Peak RSS is the largest single process, not the tree's sum."""
52_WORK_DIR_PREFIX = "vep-bench-endtoend-"
55@register_runner("bench.endtoend")
56class Runner:
57 """End-to-end benchmark runner for full CLI configurations.
59 The gate runs first and compares outputs rather than in-memory terms: a configuration whose
60 annotated VCF disagrees with the reference's is not timed. Each run is a separate process given
61 this working copy on ``PYTHONPATH``, so what is measured is the tree the benchmark was started
62 from.
64 Attributes:
65 name (ClassVar[str]): The registry name.
66 sections (ClassVar[tuple[str, ...]]): The configuration sections read.
67 description (ClassVar[str]): One-line description for the subcommand list.
68 """
70 name: ClassVar[str] = "bench.endtoend"
71 sections: ClassVar[tuple[str, ...]] = ("logging", "corpus", "bench", "bench_endtoend")
72 description: ClassVar[str] = "time whole command-line runs over a corpus on disk"
74 def __init__(self, config: Config) -> None:
75 """Hold the configuration."""
76 self.config = config
78 def run(self) -> ExitCode:
79 """Prepare the corpus, gate, measure, report, and clean up after itself."""
80 endtoend = self.config.bench_endtoend
81 try:
82 strategies = common.resolve_strategies(endtoend.strategies, consequence_strategies())
83 configurations = build_configurations(strategies, endtoend.caches, endtoend.batch_size)
84 common.table_format(self.config)
85 except ValueError as problem:
86 logger.error("%s", problem)
87 return ExitCode.USAGE
89 workspace = Workspace(directory=self._directory(), clean=endtoend.clean)
90 try:
91 return self._measure(workspace, configurations)
92 finally:
93 workspace.close()
95 def _directory(self) -> Path:
96 """Return where the corpus, its indexes and the run outputs go."""
97 chosen = self.config.bench_endtoend.work_dir or self.config.corpus.corpus_dir
98 if chosen is not None:
99 return chosen
100 return Path(tempfile.gettempdir()) / f"{_WORK_DIR_PREFIX}{os.getpid()}"
102 def _measure(self, workspace: Workspace, configurations: list[Configuration]) -> ExitCode:
103 """Run every configuration over the prepared corpus and report the timings."""
104 spec = CorpusSpec.from_options(self.config.corpus)
105 workspace.open()
106 try:
107 with build_corpus(spec) as corpus:
108 workspace.materialise(corpus)
109 workspace.index()
110 except MissingTool as missing:
111 logger.error("%s", missing)
112 return ExitCode.USAGE
113 except subprocess.CalledProcessError as failure:
114 logger.error("indexing the corpus failed: %s", failure)
115 return ExitCode.FAILURE
117 variants = workspace.variant_count()
118 runs = [
119 (configuration, processes)
120 for configuration in configurations
121 for processes in self.config.bench_endtoend.processes
122 ]
124 try:
125 if not self.config.bench.no_gate and not self._gate(workspace, runs):
126 return ExitCode.FAILURE
127 rows = self._time(workspace, runs, corpus=self.config.corpus.kind, variants=variants)
128 except subprocess.CalledProcessError as failure:
129 logger.error("a run failed (%s):\n%s", failure.returncode, failure.stderr)
130 return ExitCode.FAILURE
132 print(f"\n{self.config.corpus.kind}: {variants} variants, {len(runs)} runs")
133 print(render_table(HEADERS, self._rows(rows), TableFormat(common.table_format(self.config))))
135 results = BenchResults(
136 info=common.run_info(self.config, self.name), rows=tuple(row.to_json() for row in rows)
137 )
138 return common.record_results(self.config, results)
140 def _gate(self, workspace: Workspace, runs: list[tuple[Configuration, int]]) -> bool:
141 """Run each configuration once and check its output against the reference's.
143 Args:
144 workspace (Workspace): The prepared corpus.
145 runs (list[tuple[Configuration, int]]): Each configuration with its worker count.
147 Returns:
148 bool: True when every configuration produced the reference's consequence terms.
149 """
150 outputs: dict[tuple[str, int], Path] = {}
151 for configuration, processes in runs:
152 outputs[(configuration.label, processes)] = self._run_for_gate(
153 workspace, configuration, processes
154 )
156 reference_key = self._reference_key(runs)
157 reference_output = outputs[reference_key]
158 for key, output in outputs.items(): 158 ↛ 172line 158 didn't jump to line 172 because the loop on line 158 didn't complete
159 if key == reference_key:
160 continue
161 mismatches = output_mismatches(reference_output, output)
162 if mismatches: 162 ↛ 158line 162 didn't jump to line 158 because the condition on line 162 was always true
163 logger.error(
164 "output gate failed for %s on %d process(es), against %s:",
165 key[0],
166 key[1],
167 reference_key[0],
168 )
169 for mismatch in mismatches:
170 logger.error(" %s", mismatch)
171 return False
172 logger.info("output gate passed: %d configurations agree with %s", len(outputs), reference_key[0])
173 return True
175 @staticmethod
176 def _reference_key(runs: list[tuple[Configuration, int]]) -> tuple[str, int]:
177 """Return the run every other run's output is compared against."""
178 for configuration, processes in runs:
179 if configuration.strategy == REFERENCE_STRATEGY:
180 return (configuration.label, processes)
181 configuration, processes = runs[0]
182 return (configuration.label, processes)
184 def _run_for_gate(self, workspace: Workspace, configuration: Configuration, processes: int) -> Path:
185 """Run one configuration once, keeping its output for the gate to compare."""
186 output = self._output_path(workspace, configuration, processes)
187 log_path = output.with_suffix(".log")
188 workspace.track(output)
189 workspace.track(log_path)
190 command = run_command(configuration, processes=processes, workspace=workspace, output=output)
191 run_once(command, log_path=log_path)
192 return output
194 def _time(
195 self,
196 workspace: Workspace,
197 runs: list[tuple[Configuration, int]],
198 *,
199 corpus: str,
200 variants: int,
201 ) -> list[EndToEndRow]:
202 """Time every run and return one row each."""
203 bench = self.config.bench
204 rows: list[EndToEndRow] = []
205 for configuration, processes in runs: 205 ↛ 221line 205 didn't jump to line 221 because the loop on line 205 didn't complete
206 output = self._output_path(workspace, configuration, processes)
207 log_path = output.with_suffix(".log")
208 workspace.track(output)
209 workspace.track(log_path)
210 command = run_command(configuration, processes=processes, workspace=workspace, output=output)
211 outcomes = time_runs(command, log_path=log_path, repeats=bench.repeats, warmup=bench.warmup)
212 rows.append(
213 summarise(
214 outcomes,
215 corpus=corpus,
216 configuration=configuration.label,
217 processes=processes,
218 variants=variants,
219 )
220 )
221 return rows
223 @staticmethod
224 def _output_path(workspace: Workspace, configuration: Configuration, processes: int) -> Path:
225 """Return where one configuration's annotated VCF goes."""
226 stem = configuration.label.replace(" ", "").replace("+", "_").replace(".", "-")
227 return workspace.directory / f"run_{stem}_p{processes}.vcf"
229 @staticmethod
230 def _rows(rows: list[EndToEndRow]) -> list[tuple[object, ...]]:
231 """Return the rows formatted, with the speed-up against the first run."""
232 reference = rows[0].seconds if rows else 0.0
233 formatted: list[tuple[object, ...]] = []
234 for row in rows:
235 speedup = reference / row.seconds if row.seconds else float("inf")
236 formatted.append(
237 (
238 row.configuration,
239 row.processes,
240 f"{row.seconds:.2f}",
241 f"{row.ms_per_1k:.1f}",
242 f"{row.variants_per_second:.1f}",
243 f"{row.peak_rss_bytes / 1024 / 1024:.0f}",
244 f"{speedup:.2f}x",
245 )
246 )
247 return formatted