Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / context_parallel / compressed_document.py: 86%
107 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"""Document-local compression blocks and compact bank ownership for contiguous CP."""
17from __future__ import annotations
19from bisect import bisect_right
20from dataclasses import dataclass
21from functools import lru_cache
22from itertools import accumulate
23from typing import Any
25import torch
26from torch.nn import functional
29@dataclass(frozen=True)
30class CompressionBoundaryRoute:
31 """Projected rows needed to complete a block owned by its final-token rank."""
33 global_start: int
34 send_offsets: tuple[int, ...]
35 input_splits: tuple[int, ...]
36 output_splits: tuple[int, ...]
37 needs_exchange: bool
40def _boundary_route(local_length: int, rank: int, intervals: tuple) -> CompressionBoundaryRoute:
41 """Derive left-boundary exchanges; all ranks enter the same collective."""
42 local_start = rank * local_length
43 global_start, global_end = intervals[rank]
44 offsets, sends, receives = [], [], []
45 for peer, (start, end) in enumerate(intervals):
46 first = max(local_start, start)
47 count = max(0, min(local_start + local_length, end) - first) if peer != rank else 0
48 offsets.append(first - local_start if count else 0)
49 sends.append(count)
50 peer_start = peer * local_length
51 receives.append(max(0, min(peer_start + local_length, global_end) - max(peer_start, global_start))
52 if peer != rank else 0)
53 needs_exchange = any(start < peer * local_length for peer, (start, _) in enumerate(intervals))
54 return CompressionBoundaryRoute(global_start, tuple(offsets), tuple(sends), tuple(receives), needs_exchange)
57@lru_cache(maxsize=128)
58def compressed_document_offsets(boundaries: tuple[int, ...], ratio: int) -> tuple[int, ...]:
59 """Return canonical K boundaries, dropping only incomplete document tails.
61 Args:
62 boundaries: Cumulative raw document boundaries, beginning at zero.
63 ratio: Positive number of raw tokens per compressed block.
65 Returns:
66 Cumulative complete-block counts in document order, beginning at zero.
67 """
68 if ratio < 1 or len(boundaries) < 2 or boundaries[0] != 0 or any(
69 end <= start for start, end in zip(boundaries, boundaries[1:])):
70 raise ValueError("Compression requires a positive ratio and strictly increasing document boundaries")
71 return (0, *accumulate((end-start)//ratio for start, end in zip(boundaries, boundaries[1:])))
74@lru_cache(maxsize=128)
75def compressed_owner_offsets(boundaries: tuple[int, ...], ratio: int, local_length: int) -> tuple[int, ...]:
76 """Assign each complete block to the raw rank containing its last token.
78 Args:
79 boundaries: Cumulative raw document boundaries, beginning at zero.
80 ratio: Positive number of raw tokens per compressed block.
81 local_length: Equal positive raw-token count on each CP rank.
83 Returns:
84 Cumulative compressed-bank offsets for each rank and the final bank end.
85 """
86 keys = compressed_document_offsets(boundaries, ratio)
87 if local_length <= 0 or boundaries[-1] % local_length:
88 raise ValueError("Compression requires equal positive raw CP shard lengths")
89 offsets = []
90 for position in range(0, boundaries[-1], local_length):
91 document = bisect_right(boundaries, position) - 1
92 offsets.append(keys[document] + (position-boundaries[document])//ratio)
93 return (*offsets, keys[-1])
96@dataclass(frozen=True)
97class DocumentCompressionPlan:
98 """Immutable block ranges; never enumerate the full sequence on the CPU."""
100 ratio: int
101 local_length: int
102 rank: int
103 counts: tuple[int, ...]
104 local_blocks: tuple[tuple[int, int], ...]
105 route: CompressionBoundaryRoute
107 def indices(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
108 """Reuse device indices for local blocks and their original rotary positions.
110 Args:
111 device: Device on which the row indices are consumed.
113 Returns:
114 Flattened pooling rows and block-start rows, relative to exchanged input.
115 """
116 return _compression_indices(self, device)
120@dataclass
121class CompactBankGather:
122 """Complete one bank gather with at most one compacting index selection."""
124 handle: Any
125 tensor: torch.Tensor
126 slots: torch.Tensor | None
128 def wait(self) -> torch.Tensor:
129 """Keep compaction in autograd so all consumers return gradients to owners.
131 Returns:
132 Complete compressed bank in canonical document order, without padding.
133 """
134 output = self.tensor if self.handle is None else self.handle.wait()
135 return output if self.slots is None else output.index_select(1, self.slots)
138@lru_cache(maxsize=128)
139def document_compression_plan(boundaries: tuple[int, ...], ratio: int, local_length: int,
140 size: int, rank: int) -> DocumentCompressionPlan:
141 """Assign complete blocks to the rank owning their final token.
143 Work on document/rank intersections rather than all global token rows.
144 The packed-sequence boundary validator owns interval validation.
146 Args:
147 boundaries: Cumulative raw document boundaries covering the global sequence.
148 ratio: Number of raw tokens per compressed block, greater than one.
149 local_length: Equal positive raw-token count on each CP rank.
150 size: Number of contiguous CP shards.
151 rank: Local rank within the CP group.
153 Returns:
154 Complete-block ownership, local block ranges, and boundary-exchange routing.
155 """
156 if ratio <= 1 or local_length <= 0 or not 0 <= rank < size:
157 raise ValueError("document block planning requires ratio > 1 and a valid contiguous CP shard")
158 if boundaries[0] != 0 or boundaries[-1] != size * local_length:
159 raise ValueError("document boundaries must cover the complete contiguous CP sequence")
160 owners = compressed_owner_offsets(boundaries, ratio, local_length)
161 counts = tuple(end-start for start, end in zip(owners, owners[1:]))
162 first_rows = [peer * local_length for peer in range(size)]
163 local_blocks = []
164 for start, end in zip(boundaries, boundaries[1:]):
165 blocks = (end - start) // ratio
166 if not blocks:
167 continue
168 first_owner = (start + ratio - 1) // local_length
169 last_owner = (start + blocks * ratio - 1) // local_length
170 for peer in range(first_owner, last_owner + 1):
171 first = max(0, (peer * local_length - start) // ratio)
172 last = min(blocks, ((peer + 1) * local_length - start) // ratio)
173 if last > first:
174 first_rows[peer] = min(first_rows[peer], start + first * ratio)
175 if peer == rank:
176 local_blocks.append((start + first * ratio, last - first))
177 intervals = tuple((first, (peer + 1) * local_length) for peer, first in enumerate(first_rows))
178 return DocumentCompressionPlan(ratio, local_length, rank, tuple(counts), tuple(local_blocks),
179 _boundary_route(local_length, rank, intervals))
182@lru_cache(maxsize=8)
183@torch.inference_mode(False)
184def _compression_indices(plan: DocumentCompressionPlan, device: torch.device) -> tuple:
185 """Reuse block rows; bound the cache since compact AG maps scale with global K."""
186 starts = [torch.arange(start, start + count * plan.ratio, plan.ratio, device=device)
187 for start, count in plan.local_blocks]
188 starts = torch.cat(starts) if starts else torch.empty(0, device=device, dtype=torch.long)
189 starts = starts - plan.route.global_start
190 rows = (starts.unsqueeze(1) + torch.arange(plan.ratio, device=device)).flatten()
191 return rows.long(), starts.long()
194@lru_cache(maxsize=8)
195@torch.inference_mode(False)
196def _bank_slots(counts: tuple[int, ...], device: torch.device) -> torch.Tensor | None:
197 """Materialize global padding maps only for the all-gather reference path."""
198 if len(set(counts)) == 1:
199 return None
200 capacity = max(counts)
201 return torch.cat([torch.arange(peer*capacity, peer*capacity+count, device=device)
202 for peer, count in enumerate(counts)])
205def launch_compressed_bank(tensor: torch.Tensor, counts: tuple[int, ...], launch: Any) -> CompactBankGather:
206 """Launch equal-capacity containers and compact padding at the consumer boundary.
208 Args:
209 tensor: Locally owned bank [batch, keys, features].
210 counts: Number of complete keys owned by each CP rank.
211 launch: Existing differentiable sequence-gather launcher, taking tensor and dimension.
212 """
213 capacity = max(counts)
214 if not capacity:
215 return CompactBankGather(None, tensor, None)
216 padded = tensor if tensor.shape[1] == capacity else functional.pad(
217 tensor, (0, 0, 0, capacity - tensor.shape[1]),
218 )
219 return CompactBankGather(launch(padded, 1), tensor, _bank_slots(counts, tensor.device))