Coverage for src/python/ensembl/vep/bench/suites.py: 100%
71 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"""The strategy x cache matrix: every configuration worth timing, and timing them.
16A registered name is a *strategy*; the caches are orthogonal to it. Timing only registered names
17would leave the configurations people actually run unmeasured, so a configuration is a strategy
18plus a cache set, and the set is chosen on the command line rather than hardcoded.
19"""
21from __future__ import annotations
23from collections.abc import Sequence
24from functools import partial
26from attrs import field, frozen
28from ensembl.vep.annotators.base import Annotator
29from ensembl.vep.annotators.factory import build_annotator
30from ensembl.vep.bench.harness import TimingPolicy, annotator_extras, fact_cost, time_best
31from ensembl.vep.models.overlap import OverlapConsequence, TranscriptVariationAllele
33__all__ = [
34 "CACHES",
35 "NO_CACHES",
36 "Configuration",
37 "MatrixRow",
38 "build_configurations",
39 "parse_cache_set",
40 "run_matrix",
41]
43CACHES = ("zonemap", "codon", "mapper")
44"""The caches a configuration can switch on, in the order a label names them."""
45NO_CACHES = "none"
48def parse_cache_set(text: str) -> frozenset[str]:
49 """Parse ``none`` or a ``+``-joined set of cache names.
51 Raises:
52 ValueError: If a name is not one of ``CACHES``.
53 """
54 names = [part.strip() for part in text.split("+") if part.strip()]
55 if names == [NO_CACHES]:
56 return frozenset()
57 unknown = sorted(set(names) - set(CACHES))
58 if unknown or not names:
59 raise ValueError(
60 f"unknown cache set {text!r}: expected {NO_CACHES!r} or a +-joined set of {', '.join(CACHES)}"
61 )
62 return frozenset(names)
65@frozen(kw_only=True, auto_attribs=True)
66class Configuration:
67 """One strategy with one set of caches.
69 Attributes:
70 strategy (str): The registered strategy.
71 caches (frozenset[str]): The caches switched on.
72 batch_size (int): Chunk size, for the strategies that batch.
73 """
75 strategy: str
76 caches: frozenset[str] = field(factory=frozenset)
77 batch_size: int = field(default=256)
79 @property
80 def label(self) -> str:
81 """Return the configuration's table label: the strategy, then its caches."""
82 if not self.caches:
83 return self.strategy
84 return f"{self.strategy} +{'+'.join(name for name in CACHES if name in self.caches)}"
86 def build(self) -> Annotator[OverlapConsequence]:
87 """Return a fresh annotator with fresh caches, so no configuration is timed warm from another."""
88 return build_annotator(
89 annotator=self.strategy,
90 batch_size=self.batch_size,
91 zone_map="zonemap" in self.caches,
92 codon_cache="codon" in self.caches,
93 mapper_cache="mapper" in self.caches,
94 )
97def build_configurations(
98 strategies: Sequence[str], cache_sets: Sequence[str], batch_size: int
99) -> list[Configuration]:
100 """Cross strategies with cache sets, strategies outermost, without repeats.
102 Raises:
103 ValueError: If a cache set does not parse.
104 """
105 parsed = [parse_cache_set(text) for text in cache_sets]
106 configurations: list[Configuration] = []
107 for strategy in strategies:
108 for caches in parsed:
109 configuration = Configuration(strategy=strategy, caches=caches, batch_size=batch_size)
110 if configuration not in configurations:
111 configurations.append(configuration)
112 return configurations
115@frozen(kw_only=True, auto_attribs=True)
116class MatrixRow:
117 """One configuration's measurements over one corpus.
119 Attributes:
120 corpus (str): The corpus measured over.
121 configuration (str): The configuration's label.
122 contexts (int): Overlaps in the corpus.
123 ms_per_1k (float): Best wall clock per thousand overlaps, one overlap at a time.
124 batch_ms_per_1k (float): The same, in chunks of the configuration's batch size.
125 facts_per_context (float): Facts computed per overlap.
126 cost_per_context (float): Declared cost charged per overlap -- the number that survives a
127 port to another language, where wall clock does not.
128 extras (dict[str, object]): Whatever instrumentation the annotator and caches expose.
129 """
131 corpus: str
132 configuration: str
133 contexts: int
134 ms_per_1k: float
135 batch_ms_per_1k: float
136 facts_per_context: float
137 cost_per_context: float
138 extras: dict[str, object] = field(factory=dict)
140 def to_json(self) -> dict[str, object]:
141 """Return the row as plain JSON-ready data."""
142 return {
143 "corpus": self.corpus,
144 "configuration": self.configuration,
145 "contexts": self.contexts,
146 "ms_per_1k": self.ms_per_1k,
147 "batch_ms_per_1k": self.batch_ms_per_1k,
148 "facts_per_context": self.facts_per_context,
149 "cost_per_context": self.cost_per_context,
150 "extras": dict(self.extras),
151 }
154def _run_single(
155 annotator: Annotator[OverlapConsequence], overlaps: Sequence[TranscriptVariationAllele]
156) -> None:
157 """Annotate every overlap one at a time."""
158 for overlap in overlaps:
159 annotator.annotate_feature_overlap(overlap)
162def _run_chunked(
163 annotator: Annotator[OverlapConsequence], overlaps: Sequence[TranscriptVariationAllele], chunk_size: int
164) -> None:
165 """Annotate every overlap in chunks."""
166 for start in range(0, len(overlaps), chunk_size):
167 annotator.annotate_feature_overlaps(list(overlaps[start : start + chunk_size]))
170def run_matrix(
171 corpus: str,
172 overlaps: Sequence[TranscriptVariationAllele],
173 configurations: Sequence[Configuration],
174 policy: TimingPolicy,
175) -> list[MatrixRow]:
176 """Measure every configuration over one corpus.
178 Each measurement builds its own annotator: one for the single-overlap timing, a clean one for
179 the fact count (instrumenting needs its own pass), and one for the batch timing.
180 """
181 rows = []
182 for configuration in configurations:
183 single = configuration.build()
184 single_timing = time_best(partial(_run_single, single, overlaps), policy)
186 counted = configuration.build()
187 facts_per_context, cost_per_context = fact_cost(counted, overlaps)
189 batched = configuration.build()
190 size = max(1, configuration.batch_size)
191 batch_timing = time_best(partial(_run_chunked, batched, overlaps, size), policy)
193 rows.append(
194 MatrixRow(
195 corpus=corpus,
196 configuration=configuration.label,
197 contexts=len(overlaps),
198 ms_per_1k=single_timing.ms_per_thousand(len(overlaps)),
199 batch_ms_per_1k=batch_timing.ms_per_thousand(len(overlaps)),
200 facts_per_context=facts_per_context,
201 cost_per_context=cost_per_context,
202 extras=annotator_extras(counted),
203 )
204 )
205 return rows