Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / auto_parallel / hyper_offload / planning / peak.py: 100%
111 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
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# ============================================================================
15"""Peak-driven residency planning using the existing trace and action IR."""
17from __future__ import annotations
19import logging
20import math
21from dataclasses import dataclass
22from itertools import accumulate
24from hyper_parallel.auto_parallel.hyper_offload.ir.schedule import (
25 ResidencyActionType,
26 ResidencySchedule,
27)
28from hyper_parallel.auto_parallel.hyper_offload.ir.trace import ActivationTrace
29from hyper_parallel.auto_parallel.hyper_offload.planning._peak_model import (
30 EvictionGap,
31 PeakProfile,
32 build_profile,
33)
34from hyper_parallel.auto_parallel.hyper_offload.planning.communication_mask import (
35 TransferPlacement,
36 limit_prefetch_advance,
37 limit_release_delay,
38 mask_communications,
39 release_checkpoints,
40)
42logger = logging.getLogger(__name__)
45@dataclass(frozen=True)
46class ScoreWeights:
47 """Weight freed bytes above coverage to avoid many tiny transfer intervals."""
49 size: float = 2.0
50 cover_start: float = 1.0
51 cover_end: float = 1.0
52 neighbor_impact: float = 1.0
55def _overlap_fraction(gap: EvictionGap, selected: list[EvictionGap]) -> float:
56 intervals = sorted(
57 (max(gap.first, other.first), min(gap.last, other.last)) for other in selected
58 )
59 covered, cursor = 0, gap.first
60 for start, end in intervals:
61 if end > max(cursor, start):
62 covered += end - max(cursor, start)
63 cursor = end
64 return covered / max(1, gap.last - gap.first)
67def _choose_gap(
68 eligible: list[EvictionGap],
69 peak: int,
70 selected: list[EvictionGap],
71 weights: ScoreWeights,
72) -> EvictionGap:
73 """Choose an eviction interval by size, peak coverage and overlap."""
74 max_size = max(gap.size_bytes for gap in eligible)
75 max_left = max(peak - gap.first for gap in eligible)
76 max_right = max(gap.end - peak for gap in eligible)
78 def score(gap: EvictionGap) -> tuple:
79 """Rank candidates with deterministic size and position tie breaks."""
80 value = (
81 weights.size * gap.size_bytes / max_size
82 + weights.cover_start * (peak - gap.first) / max_left
83 + weights.cover_end * (gap.end - peak) / max_right
84 - weights.neighbor_impact * _overlap_fraction(gap, selected)
85 )
86 return value, gap.size_bytes, gap.end - gap.start, gap.start, -gap.storage_id
88 return max(eligible, key=score)
91def _select_gaps(
92 resident: list[int], gaps: list[EvictionGap], limit: int, weights: ScoreWeights,
93 preferred: set[tuple[int, int, int]] | None = None,
94) -> list[EvictionGap]:
95 """Select eviction intervals until reducible peaks fit the budget."""
96 remaining, selected = list(gaps), []
97 delta = [0] * (len(resident) + 1)
98 for gap in gaps:
99 delta[gap.start + 1] += 1
100 delta[gap.end] -= 1
101 covering = list(accumulate(delta[:-1]))
102 while remaining:
103 # An unavoidable operator peak must not hide other reducible peaks.
104 reducible = (
105 slot
106 for slot, count in enumerate(covering)
107 if count and resident[slot] > limit
108 )
109 peak = max(reducible, key=lambda slot: (resident[slot], slot), default=None)
110 if peak is None:
111 break
112 eligible = [gap for gap in remaining if gap.start < peak < gap.end]
113 native = [
114 gap for gap in eligible
115 if preferred and (gap.storage_id, gap.start, gap.end) in preferred
116 ]
117 chosen = _choose_gap(native or eligible, peak, selected, weights)
118 selected.append(chosen)
119 remaining.remove(chosen)
120 for slot in range(chosen.start + 1, chosen.end):
121 resident[slot] -= chosen.size_bytes
122 covering[slot] -= 1
123 return selected
126def _emit_schedule(
127 placements: list[TransferPlacement], last_uses: dict[int, int], retained: set[int],
128 checkpoint_ops: set[int],
129) -> ResidencySchedule:
130 """Translate selected intervals into ordered residency actions."""
131 schedule = ResidencySchedule()
132 for placement in sorted(
133 placements,
134 key=lambda item: (item.prefetch_before, item.gap.end, item.gap.storage_id),
135 ):
136 sid = placement.gap.storage_id
137 schedule.add_pre(placement.prefetch_before, ResidencyActionType.COPY_H2D, sid)
138 # Retire the old snapshot before a consumer may mutate this storage.
139 # The existing pool defers reuse until the H2D completion event.
140 schedule.add_pre(
141 placement.prefetch_before, ResidencyActionType.RELEASE_HOST, sid
142 )
143 posts = []
144 for placement in placements:
145 sid = placement.gap.storage_id
146 posts.append((placement.copy_after, 0, sid, ResidencyActionType.COPY_D2H))
147 deadline = (
148 placement.release_after
149 if placement.release_deadline is None
150 else placement.release_deadline
151 )
152 # A hard fence on an unrelated wrapper-only op expands management.
153 # An earlier native boundary is safe, but never cross the last use.
154 while deadline > placement.gap.start and deadline not in checkpoint_ops:
155 deadline -= 1
156 posts.extend(
157 (op, 1, sid, ResidencyActionType.TRY_RELEASE_DEVICE)
158 for op in release_checkpoints(placement)
159 if op in checkpoint_ops and op < deadline
160 )
161 posts.append(
162 (deadline, 1, sid, ResidencyActionType.RELEASE_DEVICE)
163 )
164 posts.extend(
165 (op, 1, sid, ResidencyActionType.RELEASE_DEVICE)
166 for sid, op in last_uses.items()
167 if sid not in retained
168 )
169 for op, _, sid, kind in sorted(posts):
170 schedule.add_post(op, kind, sid)
171 return schedule
174class PeakResidencyPlanner:
175 """Select idle storage gaps covering the current peak, then mask transfers.
177 Prefer trace-supplied native autograd intervals when they cover the peak;
178 use other candidates when needed to satisfy the same memory budget.
180 Args:
181 enable_communication_masking: Delay releases and advance H2D copies in
182 available memory. Runtime events enforce transfer dependencies.
183 weights: Normalized size, coverage and neighboring-lifetime weights.
184 """
186 def __init__(
187 self,
188 *,
189 enable_communication_masking: bool = True,
190 weights: ScoreWeights | None = None,
191 ) -> None:
192 """Configure peak selection and optional communication masking."""
193 if not isinstance(enable_communication_masking, bool):
194 raise TypeError("enable_communication_masking must be a bool")
195 self.enable_communication_masking = enable_communication_masking
196 self.weights = weights if weights is not None else ScoreWeights()
197 if not all(
198 math.isfinite(value) and value >= 0 for value in vars(self.weights).values()
199 ):
200 raise ValueError("peak score weights must be finite and nonnegative")
202 def _reserve_framework_workspace(
203 self, trace: ActivationTrace, profile: PeakProfile, selected: list[EvictionGap], limit: int,
204 ) -> int:
205 """Select extra native intervals and return the workspace-adjusted limit.
207 Args:
208 trace: Recorded framework allocation sizes and native interval hints.
209 profile: Residency profile updated by the extra selections.
210 selected: Existing selections extended with extra native intervals.
211 limit: Original activation-residency limit in bytes.
212 """
213 workspace = trace.framework_allocation_bytes
214 if isinstance(workspace, bool) or not isinstance(workspace, int) or workspace < 0:
215 raise ValueError("framework_allocation_bytes must be a nonnegative integer")
216 if not workspace:
217 return limit
218 # Framework dtype conversions are outside activation ownership.
219 # Leave room for their large contiguous allocation plus allocator
220 # split slack, using only native-save intervals for extra offload.
221 limit = max(0, limit - 2 * workspace)
222 preferred = set(trace.preferred_eviction_gaps)
223 remaining = [
224 gap for gap in profile.gaps
225 if gap not in selected and (gap.storage_id, gap.start, gap.end) in preferred
226 ]
227 selected.extend(_select_gaps(profile.resident_bytes, remaining, limit, self.weights, preferred))
228 return limit
230 def build(self, trace: ActivationTrace) -> ResidencySchedule:
231 """Build actions compatible with the baseline replay executor.
233 The limit covers trace-managed storage bytes, not total device memory.
234 Irreducible operator peaks are reported; a schedule is not an OOM or
235 performance guarantee. Input trace data is never modified.
237 Args:
238 trace: Warmup operations, storage lifetimes and allocation metadata.
239 """
240 limit = trace.memory_limit_bytes
241 if limit is None:
242 return ResidencySchedule()
243 if isinstance(limit, bool) or not isinstance(limit, int) or limit < 0:
244 raise ValueError("memory_limit_bytes must be a nonnegative integer or None")
245 profile = build_profile(trace)
246 selected = _select_gaps(
247 profile.resident_bytes, profile.gaps, limit, self.weights, set(trace.preferred_eviction_gaps)
248 )
249 limit = self._reserve_framework_workspace(trace, profile, selected, limit)
250 if self.enable_communication_masking:
251 placements = mask_communications(selected, profile.resident_bytes, limit)
252 limit_prefetch_advance(
253 placements, profile.resident_bytes, [op.duration_ms for op in trace.ops], trace.h2d_bandwidth_gbps
254 )
255 limit_release_delay(
256 placements, [op.duration_ms for op in trace.ops], trace.d2h_bandwidth_gbps
257 )
258 else:
259 placements = [
260 TransferPlacement(gap, gap.start, gap.start, gap.end)
261 for gap in selected
262 ]
263 peak = max(profile.resident_bytes, default=0)
264 if peak > limit:
265 logger.warning(
266 "Peak planner cannot meet budget: planned peak=%d bytes, limit=%d bytes",
267 peak,
268 limit,
269 )
270 logger.info(
271 "Peak planner selected %d/%d gaps; planned peak=%d bytes, budget=%d bytes",
272 len(selected),
273 len(profile.gaps),
274 peak,
275 limit,
276 )
277 # Optional checks must not turn wrapper-only detach/framework reads
278 # into required replay operations or expand managed tensor bindings.
279 checkpoint_ops = {
280 index for index, op in enumerate(trace.ops)
281 if op.name != "detach.default" and not op.name.startswith("framework_read:")
282 }
283 return _emit_schedule(placements, profile.last_uses, trace.retained_sids, checkpoint_ops)