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"""Storage lifetimes and safe eviction gaps for peak planning."""
16
17from __future__ import annotations
18
19from dataclasses import dataclass
20from itertools import accumulate, pairwise
21
22from hyper_parallel.auto_parallel.hyper_offload.ir.trace import (
23 AccessKind,
24 ActivationTrace,
25)
26
27
28@dataclass(frozen=True)
29class EvictionGap:
30 """One idle interval; endpoints must remain device resident."""
31
32 storage_id: int
33 size_bytes: int
34 start: int
35 end: int
36 copy_start: int
37 first: int
38 last: int
39
40
41@dataclass
42class PeakProfile:
43 """Per-operator residency, safe gaps, and terminal releases."""
44
45 resident_bytes: list[int]
46 gaps: list[EvictionGap]
47 last_uses: dict[int, int]
48
49
50def build_profile(trace: ActivationTrace) -> PeakProfile:
51 """Account for each storage once, including retained output lifetimes.
52
53 READ/WRITE pairs at the same operator share a residency slot. Every WRITE
54 is conservatively a snapshot barrier, including view outputs recorded as
55 writes by the baseline tracer.
56 """
57 accesses = {}
58 for op_id, op in enumerate(trace.ops):
59 for access in op.accesses:
60 if access.op_id != op_id:
61 raise ValueError("storage access op_id must match its trace position")
62 if access.kind not in (AccessKind.READ, AccessKind.WRITE):
63 raise ValueError("unknown storage access kind")
64 accesses.setdefault(access.storage_id, {}).setdefault(op_id, set()).add(
65 access.kind
66 )
67 delta = [0] * (len(trace.ops) + 1)
68 gaps, last_uses = [], {}
69 for sid, by_op in accesses.items():
70 size = trace.storage_sizes.get(sid)
71 if isinstance(size, bool) or not isinstance(size, int) or size < 0:
72 raise ValueError(f"storage {sid} requires a nonnegative integer byte size")
73 positions = sorted(by_op)
74 first, last = positions[0], positions[-1]
75 resident_end = len(trace.ops) - 1 if sid in trace.retained_sids else last
76 delta[first] += size
77 delta[resident_end + 1] -= size
78 last_uses[sid] = last
79 if sid in trace.retained_sids:
80 continue
81 latest_write = first
82 for start, end in pairwise(positions):
83 if AccessKind.WRITE in by_op[start]:
84 latest_write = start
85 if end > start + 1 and size:
86 gaps.append(
87 EvictionGap(sid, size, start, end, latest_write, first, last)
88 )
89 return PeakProfile(list(accumulate(delta[:-1])), gaps, last_uses)