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"""Overlap selected transfers without exceeding the planned resident budget."""
16
17from __future__ import annotations
18
19import math
20from bisect import bisect_left, bisect_right
21from dataclasses import dataclass
22from itertools import accumulate
23
24from hyper_parallel.auto_parallel.hyper_offload.planning._peak_model import EvictionGap
25
26
27# Warmup includes dispatch and synchronization overhead that replay can avoid.
28# Preserve four transfer durations of H2D lead as a margin for faster replay.
29PREFETCH_LEAD_COPIES = 4.0
30
31
32@dataclass
33class TransferPlacement:
34 """D2H post-op, device release post-op, and H2D pre-op positions."""
35
36 gap: EvictionGap
37 copy_after: int
38 release_after: int
39 prefetch_before: int
40 release_deadline: int | None = None
41
42
43def mask_communications(
44 selected: list[EvictionGap], resident_bytes: list[int], limit: int
45) -> list[TransferPlacement]:
46 """Delay device releases and advance prefetches within spare device memory.
47
48 The input profile describes selected gaps before overlap and is updated
49 in place. A snapshot cannot cross an earlier selected gap of the same
50 storage: the baseline runtime must restore and retire that snapshot first.
51 Runtime events remain responsible for actual transfer completion.
52 """
53 placements = []
54 restored_at = {}
55 for gap in sorted(
56 selected, key=lambda item: (item.start, item.end, item.storage_id)
57 ):
58 copy_after = max(
59 gap.copy_start, restored_at.get(gap.storage_id, gap.copy_start)
60 )
61 placements.append(TransferPlacement(gap, copy_after, gap.start, gap.end))
62 restored_at[gap.storage_id] = gap.end
63
64 previous_prefetch = 0
65 for placement in sorted(
66 placements, key=lambda item: (item.gap.end, item.gap.start, item.gap.storage_id)
67 ):
68 gap = placement.gap
69 lower = max(placement.release_after + 1, previous_prefetch)
70 while placement.prefetch_before > lower:
71 slot = placement.prefetch_before - 1
72 if resident_bytes[slot] + gap.size_bytes > limit:
73 break
74 resident_bytes[slot] += gap.size_bytes
75 placement.prefetch_before = slot
76 previous_prefetch = placement.prefetch_before
77
78 # Spend spare residency on H2D overlap first; delaying D2H release is
79 # useful only when it does not push a prefetch past its source retirement.
80 next_release = len(resident_bytes)
81 for placement in sorted(
82 placements, key=lambda item: (item.copy_after, item.gap.start), reverse=True
83 ):
84 gap = placement.gap
85 upper = min(gap.end - 1, placement.prefetch_before - 1, next_release)
86 while placement.release_after < upper:
87 slot = placement.release_after + 1
88 if resident_bytes[slot] + gap.size_bytes > limit:
89 break
90 resident_bytes[slot] += gap.size_bytes
91 placement.release_after = slot
92 next_release = placement.release_after
93 return placements
94
95
96def limit_release_delay(
97 placements: list[TransferPlacement], durations_ms: list[float], bandwidth_gbps: float
98) -> None:
99 """Estimate when to begin nonblocking source retirement checks.
100
101 Preserve the mask's hard memory deadline separately from the estimated
102 completion position. Warmup timing may overestimate replay computation,
103 so an estimate must not force compute to wait for unfinished transfers.
104 Missing timing keeps the memory-only mask. H2D positions stay unchanged.
105 """
106 if not placements:
107 return
108 if (
109 not math.isfinite(bandwidth_gbps)
110 or bandwidth_gbps <= 0
111 or any(not math.isfinite(value) or value < 0 for value in durations_ms)
112 or not any(durations_ms)
113 ):
114 return
115 ends = list(accumulate(durations_ms))
116 copy_complete_ms = 0.0
117 for placement in sorted(
118 placements, key=lambda item: (item.copy_after, item.gap.storage_id)
119 ):
120 transfer_ms = placement.gap.size_bytes * 1000 / (bandwidth_gbps * 1024**3)
121 copy_complete_ms = max(copy_complete_ms, ends[placement.copy_after]) + transfer_ms
122 ready = bisect_left(
123 ends, copy_complete_ms, placement.gap.start, placement.release_after + 1
124 )
125 placement.release_deadline = placement.release_after
126 placement.release_after = min(ready, placement.release_deadline)
127
128
129def limit_prefetch_advance(
130 placements: list[TransferPlacement], resident_bytes: list[int],
131 durations_ms: list[float], bandwidth_gbps: float,
132) -> None:
133 """Keep H2D lead time proportional to queued transfer work.
134
135 Memory headroom alone can move many restores hundreds of milliseconds
136 before their consumers. Holding those destinations fragments the allocator
137 and competes with backward workspaces. Schedule the copy queue backwards
138 from consumer deadlines with a margin for faster replay than warmup.
139 Moving a prefetch later only reduces the memory-only mask's residency.
140 """
141 if (
142 not placements or not math.isfinite(bandwidth_gbps) or bandwidth_gbps <= 0
143 or any(not math.isfinite(value) or value < 0 for value in durations_ms)
144 or not any(durations_ms)
145 ):
146 return
147 starts = [0.0, *accumulate(durations_ms)]
148 next_start = math.inf
149 for placement in sorted(
150 placements, key=lambda item: (item.gap.end, item.gap.storage_id), reverse=True
151 ):
152 transfer_ms = placement.gap.size_bytes * 1000 / (bandwidth_gbps * 1024**3)
153 start_ms = min(starts[placement.gap.end], next_start) - PREFETCH_LEAD_COPIES * transfer_ms
154 target = max(placement.prefetch_before, bisect_right(starts, start_ms) - 1)
155 target = min(target, placement.gap.end)
156 for slot in range(placement.prefetch_before, target):
157 resident_bytes[slot] -= placement.gap.size_bytes
158 placement.prefetch_before = target
159 next_start = starts[target]
160
161
162def release_checkpoints(placement: TransferPlacement) -> list[int]:
163 """Return sparse completion checks strictly before the memory deadline.
164
165 Exponentially spaced operator boundaries bound event-query overhead when
166 the host runs ahead of the copy stream. All checkpoints are after the
167 last source use; the original release still enforces the memory budget.
168 """
169 deadline = placement.release_deadline
170 if deadline is None:
171 return []
172 checkpoints = []
173 position = placement.release_after
174 distance = max(1, position - placement.copy_after)
175 while position < deadline:
176 checkpoints.append(position)
177 position += distance
178 distance *= 2
179 return checkpoints