Coverage for src/python/ensembl/vep/bench/sweep.py: 95%
56 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"""Sweeping one numeric annotation setting and timing each value.
16Every value is sanity-checked against the reference strategy before it is timed: a setting that
17changes the answer is a bug, not a speed-up. The chunking follows the strategy. A Python batch
18strategy chunks internally by its own ``batch_size``, so it is handed the whole corpus at once; the
19native kernels chunk nowhere else, so for them the swept batch size is the chunk handed over.
20"""
22from __future__ import annotations
24from collections.abc import Sequence
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 KERNELS_STRATEGY, REFERENCE_STRATEGY, TimingPolicy, terms_of, time_best
31from ensembl.vep.caches.zone_map import DEFAULT_ZONE_MAP_BYTES
32from ensembl.vep.config.sections.bench.sweep import SWEEPABLE_KNOBS
33from ensembl.vep.models.overlap import OverlapConsequence, TranscriptVariationAllele
35__all__ = [
36 "DEFAULT_BATCH_STRATEGIES",
37 "SANITY_CHECK_COUNT",
38 "SWEEPABLE_KNOBS",
39 "Sweep",
40 "SweepPoint",
41 "sweep_strategy",
42]
44SANITY_CHECK_COUNT = 64
45"""Overlaps each swept value is checked on before it is timed."""
46DEFAULT_BATCH_STRATEGIES = ("consequence.columnar-staged", KERNELS_STRATEGY)
48_DEFAULT_BATCH_SIZE = 256
49_DEFAULT_CODON_CACHE_ENTRIES = 65536
50_DEFAULT_MAPPER_CACHE_BYTES = 64 * 1024 * 1024
53@frozen(kw_only=True, auto_attribs=True)
54class Sweep:
55 """A setting and the values to try.
57 Attributes:
58 knob (str): One of ``SWEEPABLE_KNOBS``.
59 values (tuple[int, ...]): The values, in order.
60 """
62 knob: str
63 values: tuple[int, ...] = field(default=())
65 def __attrs_post_init__(self) -> None:
66 """Reject a setting that cannot be swept."""
67 if self.knob not in SWEEPABLE_KNOBS:
68 raise ValueError(f"cannot sweep {self.knob!r}; expected one of {', '.join(SWEEPABLE_KNOBS)}")
71@frozen(kw_only=True, auto_attribs=True)
72class SweepPoint:
73 """One strategy at one value of the swept setting.
75 Attributes:
76 corpus (str): The corpus measured over.
77 strategy (str): The strategy.
78 knob (str): The swept setting.
79 value (int): Its value for this point.
80 ms_per_1k (float): Best wall clock per thousand overlaps.
81 """
83 corpus: str
84 strategy: str
85 knob: str
86 value: int
87 ms_per_1k: float
89 @property
90 def configuration(self) -> str:
91 """Return the point's name in a results file."""
92 return f"{self.strategy} {self.knob}={self.value}"
94 def to_json(self) -> dict[str, object]:
95 """Return the point as plain JSON-ready data."""
96 return {
97 "corpus": self.corpus,
98 "configuration": self.configuration,
99 "strategy": self.strategy,
100 "knob": self.knob,
101 "value": self.value,
102 "ms_per_1k": self.ms_per_1k,
103 }
106def _annotator_at(strategy: str, knob: str, value: int) -> Annotator[OverlapConsequence]:
107 """Build a strategy with one setting at the swept value, and the cache it needs switched on."""
108 return build_annotator(
109 annotator=strategy,
110 batch_size=value if knob == "batch_size" else _DEFAULT_BATCH_SIZE,
111 zone_map=knob == "zone_map_bytes",
112 zone_map_bytes=value if knob == "zone_map_bytes" else DEFAULT_ZONE_MAP_BYTES,
113 codon_cache=knob == "codon_cache_entries",
114 codon_cache_entries=value if knob == "codon_cache_entries" else _DEFAULT_CODON_CACHE_ENTRIES,
115 mapper_cache=knob == "mapper_cache_bytes",
116 mapper_cache_bytes=value if knob == "mapper_cache_bytes" else _DEFAULT_MAPPER_CACHE_BYTES,
117 )
120def sweep_strategy(
121 corpus: str,
122 strategy: str,
123 overlaps: Sequence[TranscriptVariationAllele],
124 sweep: Sweep,
125 policy: TimingPolicy,
126) -> tuple[list[SweepPoint], list[str]]:
127 """Time one strategy at every value of a setting, checking each value first.
129 Args:
130 corpus (str): The corpus's label.
131 strategy (str): The strategy to sweep.
132 overlaps (Sequence[TranscriptVariationAllele]): The corpus.
133 sweep (Sweep): The setting and its values.
134 policy (TimingPolicy): How to time.
136 Returns:
137 tuple[list[SweepPoint], list[str]]: The timed points, and one line per value that changed
138 the answer -- which is not timed.
139 """
140 checked = list(overlaps[:SANITY_CHECK_COUNT])
141 reference = build_annotator(annotator=REFERENCE_STRATEGY)
142 expected = [terms_of(reference.annotate_feature_overlap(overlap)) for overlap in checked]
144 points: list[SweepPoint] = []
145 failures: list[str] = []
146 for value in sweep.values:
147 annotator = _annotator_at(strategy, sweep.knob, value)
148 actual = [terms_of(consequences) for consequences in annotator.annotate_feature_overlaps(checked)]
149 if actual != expected: 149 ↛ 150line 149 didn't jump to line 150 because the condition on line 149 was never true
150 failures.append(
151 f"{strategy} at {sweep.knob}={value} disagrees with {REFERENCE_STRATEGY} "
152 f"on the first {len(checked)} overlaps"
153 )
154 continue
155 chunk_size = (
156 value if sweep.knob == "batch_size" and strategy == KERNELS_STRATEGY else max(1, len(overlaps))
157 )
159 def run_once(annotator: Annotator[OverlapConsequence] = annotator, size: int = chunk_size) -> None:
160 for start in range(0, len(overlaps), size):
161 annotator.annotate_feature_overlaps(list(overlaps[start : start + size]))
163 timing = time_best(run_once, policy)
164 points.append(
165 SweepPoint(
166 corpus=corpus,
167 strategy=strategy,
168 knob=sweep.knob,
169 value=value,
170 ms_per_1k=timing.ms_per_thousand(len(overlaps)),
171 )
172 )
173 return points, failures