Coverage for src/python/ensembl/vep/runner/bench/matrix.py: 90%

65 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"""Strategy and cache benchmark matrix.""" 

15 

16from __future__ import annotations 

17 

18import logging 

19from typing import ClassVar 

20 

21from ensembl.vep.bench.baseline import BenchResults 

22from ensembl.vep.bench.harness import consequence_strategies, native_kernels_available 

23from ensembl.vep.bench.suites import MatrixRow, build_configurations, run_matrix 

24from ensembl.vep.config import Config 

25from ensembl.vep.corpus.registry import CorpusOptionsError 

26from ensembl.vep.render.table import TableFormat, render_table 

27from ensembl.vep.runner.base import ExitCode 

28from ensembl.vep.runner.bench import common 

29from ensembl.vep.runner.registry import register_runner 

30 

31__all__ = ["Runner"] 

32 

33logger = logging.getLogger(__name__) 

34 

35HEADERS = ("Configuration", "ms/1k ctx", "batch ms/1k ctx", "facts/ctx", "cost/ctx", "vs linear") 

36EXTRAS_HEADERS = ("Configuration", "Instrumentation") 

37 

38 

39@register_runner("bench.matrix") 

40class Runner: 

41 """Benchmark runner for strategy and cache combinations. 

42 

43 ``cost/ctx`` and wall clock rank strategies differently on purpose: the cost is the number that 

44 survives a port to another language, while wall clock here is dominated by interpreter dispatch. 

45 

46 Attributes: 

47 name (ClassVar[str]): The registry name. 

48 sections (ClassVar[tuple[str, ...]]): The configuration sections read. 

49 description (ClassVar[str]): One-line description for the subcommand list. 

50 """ 

51 

52 name: ClassVar[str] = "bench.matrix" 

53 sections: ClassVar[tuple[str, ...]] = ("logging", "corpus", "bench", "bench_matrix") 

54 description: ClassVar[str] = "time every strategy and cache configuration over a corpus" 

55 

56 def __init__(self, config: Config) -> None: 

57 """Hold the configuration.""" 

58 self.config = config 

59 

60 def run(self) -> ExitCode: 

61 """Gate, measure, report, and record.""" 

62 matrix = self.config.bench_matrix 

63 try: 

64 strategies = common.resolve_strategies(matrix.strategies, consequence_strategies()) 

65 configurations = build_configurations(strategies, matrix.caches, matrix.batch_size) 

66 table_format = TableFormat(common.table_format(self.config)) 

67 except ValueError as problem: 

68 logger.error("%s", problem) 

69 return ExitCode.USAGE 

70 if not native_kernels_available(): 70 ↛ 71line 70 didn't jump to line 71 because the condition on line 70 was never true

71 logger.info( 

72 "consequence.columnar-kernels is not registered here: the native extension is not built" 

73 ) 

74 

75 try: 

76 with common.corpora(self.config) as labelled: 

77 if not self.config.bench.no_gate and not common.gate(labelled): 77 ↛ 78line 77 didn't jump to line 78 because the condition on line 77 was never true

78 return ExitCode.FAILURE 

79 

80 rows: list[MatrixRow] = [] 

81 for label, overlaps in labelled: 

82 corpus_rows = run_matrix(label, overlaps, configurations, common.policy(self.config)) 

83 print(f"\n{label}: {len(overlaps)} overlaps, {len(configurations)} configurations") 

84 print(render_table(HEADERS, self._rows(corpus_rows), table_format)) 

85 extras = [ 

86 (row.configuration, _format_extras(row.extras)) for row in corpus_rows if row.extras 

87 ] 

88 if extras: 88 ↛ 90line 88 didn't jump to line 90 because the condition on line 88 was always true

89 print(render_table(EXTRAS_HEADERS, extras, table_format)) 

90 rows.extend(corpus_rows) 

91 except CorpusOptionsError as unusable: 

92 logger.error("%s", unusable) 

93 return ExitCode.USAGE 

94 

95 results = BenchResults( 

96 info=common.run_info(self.config, self.name), rows=tuple(row.to_json() for row in rows) 

97 ) 

98 return common.record_results(self.config, results) 

99 

100 @staticmethod 

101 def _rows(corpus_rows: list[MatrixRow]) -> list[tuple[object, ...]]: 

102 """Return a corpus's rows formatted, with the speed-up against the first configuration.""" 

103 reference = corpus_rows[0].ms_per_1k if corpus_rows else 0.0 

104 formatted: list[tuple[object, ...]] = [] 

105 for row in corpus_rows: 

106 speedup = reference / row.ms_per_1k if row.ms_per_1k else float("inf") 

107 formatted.append( 

108 ( 

109 row.configuration, 

110 f"{row.ms_per_1k:.3f}", 

111 f"{row.batch_ms_per_1k:.3f}", 

112 f"{row.facts_per_context:.2f}", 

113 f"{row.cost_per_context:.2f}", 

114 f"{speedup:.2f}x", 

115 ) 

116 ) 

117 return formatted 

118 

119 

120def _format_extras(extras: dict[str, object]) -> str: 

121 """Return instrumentation as one line of key=value pairs.""" 

122 parts = [] 

123 for key, value in extras.items(): 

124 parts.append(f"{key}={value:.4f}" if isinstance(value, float) else f"{key}={value}") 

125 return ", ".join(parts)