Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / context_parallel / ring_layout.py: 86%
198 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-aware Ring blocks and differentiable owner/worker layout conversion."""
17from __future__ import annotations
19from bisect import bisect_right
20from dataclasses import dataclass
21from functools import lru_cache
22from itertools import accumulate, groupby
23from typing import Any
25import torch # pylint: disable=forbidden-backend-import
27from hyper_parallel.core.utils.communication import differentiable_all_to_all_single
28from hyper_parallel.distributed.context_parallel.query_balance import (
29 QueryTask, query_route, query_task_plan, query_task_plan_in_document_rings,
30)
33@dataclass(frozen=True)
34class AttentionBlock:
35 """One valid Q/K rectangle, optionally causal with bottom-right alignment."""
37 query_start: int
38 query_end: int
39 key_start: int
40 key_end: int
41 causal: bool = False
44@dataclass(frozen=True)
45class RingTaskPlan:
46 """Global ownership and this rank's executable blocks; contains no activations."""
48 assignments: tuple
49 route: Any
50 blocks: tuple[tuple[AttentionBlock, ...], ...]
51 batches: tuple[tuple[tuple[AttentionBlock, ...], ...], ...]
52 capacity: int
53 local_tokens: int
54 fast_zigzag: bool
57@dataclass(frozen=True)
58class PrunedRingPlan:
59 """Bound document-local KV routes for local or subring-balanced queries."""
61 spans: tuple[tuple[tuple[int, int], ...], ...]
62 source_spans: tuple[tuple[tuple[int, int], ...], ...]
63 key_tasks: tuple[tuple[QueryTask, ...], ...]
64 counts: tuple[int, ...]
65 capacity: int
66 blocks: tuple[tuple[AttentionBlock, ...], ...]
67 batches: tuple
68 local_blocks: tuple[AttentionBlock, ...]
69 local_batches: tuple
70 hops: tuple[int, ...]
73def _document_ranges(tasks):
74 cursor, result = 0, {}
75 for document, grouped in groupby(tasks, key=lambda task: task.document):
76 parts = tuple(grouped)
77 ends = tuple(accumulate(task.length for task in parts))
78 result[document] = (cursor, parts, ends)
79 cursor += ends[-1]
80 return result
83def _document_blocks(query_tasks, key_tasks, causal):
84 """Coalesce each query's visible KV prefix in the compact owner buffer.
86 Different owners have disjoint original token intervals. Remote causal blocks
87 are therefore full rectangles; own-document blocks are causal in compact order.
88 Each real Q row occurs at most once in a round, including across document gaps.
89 """
90 queries, keys = _document_ranges(query_tasks), _document_ranges(key_tasks)
91 blocks = []
92 same_owner = query_tasks == key_tasks
93 for document, (query_start, parts, query_ends) in queries.items():
94 if document not in keys:
95 continue
96 key_start, key_parts, key_ends = keys[document]
97 if same_owner or not causal:
98 blocks.append(AttentionBlock(query_start, query_start + query_ends[-1],
99 key_start, key_start + key_ends[-1], causal and same_owner))
100 continue
101 ends = tuple(part.end for part in key_parts)
102 offset = query_start
103 for query in parts:
104 count = bisect_right(ends, query.start)
105 if count:
106 key_end = key_start + key_ends[count - 1]
107 if (blocks and blocks[-1].query_end == offset and blocks[-1].key_start == key_start
108 and blocks[-1].key_end == key_end and not blocks[-1].causal):
109 previous = blocks.pop()
110 blocks.append(AttentionBlock(previous.query_start, offset + query.length, key_start, key_end))
111 else:
112 blocks.append(AttentionBlock(offset, offset + query.length, key_start, key_end))
113 offset += query.length
114 return tuple(blocks)
117def _document_blocks_between(query_tasks, key_tasks, causal):
118 """Plan exact blocks when a worker's queries and local keys have different owners."""
119 query_offsets, key_offsets = {}, {}
120 query_cursor = key_cursor = 0
121 for task in query_tasks:
122 query_offsets[task] = query_cursor
123 query_cursor += task.length
124 for task in key_tasks:
125 key_offsets[task] = key_cursor
126 key_cursor += task.length
128 keys_by_document = {}
129 for task in key_tasks:
130 keys_by_document.setdefault(task.document, []).append(task)
132 blocks = []
133 for query in query_tasks:
134 q_start, q_end = query.start, query.end
135 q_offset = query_offsets[query]
136 for key in keys_by_document.get(query.document, ()):
137 k_start, k_end = key.start, key.end
138 k_offset = key_offsets[key]
139 if not causal:
140 blocks.append(AttentionBlock(q_offset, q_offset + query.length,
141 k_offset, k_offset + key.length))
142 continue
143 if k_end <= q_start:
144 blocks.append(AttentionBlock(q_offset, q_offset + query.length,
145 k_offset, k_offset + key.length))
146 continue
147 if k_start >= q_end:
148 continue
150 diagonal_start, diagonal_end = max(q_start, k_start), min(q_end, k_end)
151 q_diagonal_start = q_offset + diagonal_start - q_start
152 q_diagonal_end = q_offset + diagonal_end - q_start
153 if k_start < diagonal_start:
154 blocks.append(AttentionBlock(q_diagonal_start, q_diagonal_end,
155 k_offset, k_offset + diagonal_start - k_start))
156 blocks.append(AttentionBlock(q_diagonal_start, q_diagonal_end,
157 k_offset + diagonal_start - k_start,
158 k_offset + diagonal_end - k_start, True))
159 if q_end > k_end:
160 q_tail = q_offset + k_end - q_start
161 blocks.append(AttentionBlock(q_tail, q_offset + query.length,
162 k_offset, k_offset + key.length))
163 return tuple(blocks)
166def _block_batches(blocks, capacity):
167 """Bound repeated KV prefixes to four transport buffers per fused call."""
168 batches, current, rows = [], [], 0
169 for block in blocks:
170 count = block.key_end - block.key_start
171 overlaps_query = any(
172 block.query_start < part.query_end and part.query_start < block.query_end
173 for part in current
174 )
175 if current and (rows + count > 4 * capacity or current[0].causal != block.causal or overlaps_query):
176 batches.append(tuple(current))
177 current, rows = [], 0
178 current.append(block)
179 rows += count
180 if current:
181 batches.append(tuple(current))
182 return tuple(batches)
185@lru_cache(maxsize=128)
186def ring_task_plan(
187 lengths: tuple[int, ...], size: int, rank: int, load_balance: str, causal: bool,
188 document_subrings: bool = False,
189) -> RingTaskPlan:
190 """Build exact document-local masks and an equal-capacity transport plan.
192 One divisible dense causal document uses one kernel per round for Zigzag.
193 Other plans decompose valid intersections into full and suffix-causal blocks.
194 Padding equalizes transport capacity only and never enters a kernel.
195 """
196 planner = query_task_plan_in_document_rings if document_subrings else query_task_plan
197 assignments = planner(lengths, size, load_balance)
198 route = query_route(assignments, lengths, rank)
199 local = sum(lengths) // size
200 paired = load_balance == "zigzag"
201 fast = paired and causal and len(lengths) == 1 and lengths[0] % (2 * size) == 0
202 if fast:
203 half = local // 2
204 blocks = tuple((AttentionBlock(0, local, 0, local, True),) if owner == rank else
205 (AttentionBlock(0, local, 0, half),) if owner < rank else
206 (AttentionBlock(half, local, 0, local),) for owner in range(size))
207 else:
208 blocks = tuple(_document_blocks(assignments[rank], tasks, causal) for tasks in assignments)
209 capacity = max(sum(task.length for task in tasks) for tasks in assignments)
210 batches = tuple(_block_batches(parts, capacity) for parts in blocks)
211 return RingTaskPlan(assignments, route, blocks, batches, capacity, local, fast)
214@lru_cache(maxsize=128)
215def pruned_ring_plan(lengths: tuple[int, ...], size: int, rank: int, causal: bool,
216 assignments: tuple | None = None) -> PrunedRingPlan:
217 """Prune KV according to the exact task assignments used by the Ring workers.
219 Query and KV tasks share a task owner after reversible QKV redistribution.
220 The packed KV spans are therefore expressed in worker-local task coordinates,
221 while ``spans`` retains the original global token coordinates for inspection.
222 """
223 if not isinstance(rank, int) or isinstance(rank, bool) or not 0 <= rank < size:
224 raise ValueError("rank must belong to the CP group")
225 query_assignments = assignments or query_task_plan_in_document_rings(lengths, size, "none")
226 if len(query_assignments) != size:
227 raise ValueError("Ring task assignments must have one entry per CP rank")
228 boundaries = (0, *accumulate(lengths))
229 owner_plans = tuple(_pruned_owner_plan(owner, tasks, query_assignments, boundaries, causal)
230 for owner, tasks in enumerate(query_assignments))
231 remote_key_tasks, spans, source_spans = tuple(zip(*owner_plans))
232 counts = tuple(sum(end - start for start, end in pieces) for pieces in spans)
233 capacity = max(1, *counts)
234 consumers = _pruned_consumers(query_assignments, remote_key_tasks, causal)
235 hops = _consumer_hops(consumers, size)
236 local_blocks, blocks = _pruned_execution_blocks(query_assignments, remote_key_tasks, rank, causal)
237 return PrunedRingPlan(
238 tuple(spans), tuple(source_spans), tuple(remote_key_tasks), counts, capacity, blocks,
239 tuple(_block_batches(parts, capacity) for parts in blocks),
240 local_blocks, _block_batches(local_blocks, capacity), hops,
241 )
244def _pruned_owner_plan(owner, key_tasks, query_assignments, boundaries, causal):
245 """Build one owner's remote KV tasks and their global/source spans."""
246 remote_tasks, spans, source_spans = [], [], []
247 source_offset = 0
248 for key in key_tasks:
249 remote_queries = [task for worker, tasks in enumerate(query_assignments) if worker != owner
250 for task in tasks if task.document == key.document]
251 remote_end = max((task.end for task in remote_queries), default=key.start)
252 key_end = min(key.end, remote_end) if causal else (key.end if remote_queries else key.start)
253 if key_end > key.start:
254 remote_tasks.append(QueryTask(key.document, key.start, key_end))
255 spans.append((boundaries[key.document] + key.start, boundaries[key.document] + key_end))
256 source_spans.append((source_offset, source_offset + key_end - key.start))
257 source_offset += key.length
258 return tuple(remote_tasks), tuple(spans), tuple(source_spans)
261def _pruned_consumers(query_assignments, remote_key_tasks, causal):
262 """List Ring workers that need each owner's pruned keys."""
263 return tuple(tuple(worker for worker, tasks in enumerate(query_assignments)
264 if worker != owner and _document_blocks_between(tasks, remote_key_tasks[owner], causal))
265 for owner in range(len(query_assignments)))
268def _consumer_hops(consumers, size):
269 """Find the maximum forward Ring distance needed by each key owner."""
270 return tuple(max(((consumer - owner) % size for consumer in workers), default=0)
271 for owner, workers in enumerate(consumers))
274def _pruned_execution_blocks(query_assignments, remote_key_tasks, rank, causal):
275 """Build this rank's local block and remote owner blocks."""
276 local_blocks = _document_blocks_between(query_assignments[rank], query_assignments[rank], causal)
277 blocks = tuple(_document_blocks_between(query_assignments[rank], remote_key_tasks[owner], causal)
278 if owner != rank else () for owner in range(len(query_assignments)))
279 return local_blocks, blocks
282@lru_cache(maxsize=32)
283@torch.inference_mode(False)
284def _route_indices(route, device):
285 return tuple(torch.tensor(rows, device=device, dtype=torch.long) for rows in
286 (route.send_rows, route.receive_rows, route.local_sources, route.local_targets))
289def redistribute_ring_rows(tensor: torch.Tensor, plan: RingTaskPlan, group: Any,
290 sequence_dim: int, *, inverse: bool = False) -> torch.Tensor:
291 """Apply a reversible all-to-all-v, keeping self-owned rows local.
293 Forward packs task rows and pads to a shared Ring buffer capacity. Inverse
294 restores original owner order and excludes padding. Both directions preserve
295 autograd, including ranks whose remote sends or receives have zero rows.
296 """
297 if len(plan.assignments) == 1:
298 return tensor
299 route = plan.route
300 send, receive, sources, targets = _route_indices(route, tensor.device)
301 inputs, outputs = route.input_splits, route.output_splits
302 count = plan.capacity
303 if inverse:
304 send, receive, sources, targets = receive, send, targets, sources
305 inputs, outputs = outputs, inputs
306 count = plan.local_tokens
307 rows = tensor.movedim(sequence_dim, 0)
308 remote = differentiable_all_to_all_single(rows.index_select(0, send).contiguous(),
309 list(inputs), list(outputs), group)
310 result = rows.new_zeros((count, *rows.shape[1:]))
311 # Destinations are unique and disjoint. Fill fresh storage in-place while
312 # retaining autograd edges even when remote sends or receives are empty.
313 result.index_put_((targets,), rows.index_select(0, sources))
314 result.index_put_((receive,), remote)
315 return result.movedim(0, sequence_dim).contiguous()
318def redistribute_ring_qkv(
319 query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
320 plan: RingTaskPlan, group: Any, sequence_dim: int, head_dim: int,
321) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
322 """Exchange Q/K/V together with one autograd-aware row collective.
324 Head counts may differ for GQA. Concatenating heads preserves each token's
325 row route and makes backward return all three gradients in one exchange.
326 """
327 if len(plan.assignments) == 1:
328 return query, key, value
329 heads = tuple(tensor.shape[head_dim] for tensor in (query, key, value))
330 packed = torch.cat((query, key, value), dim=head_dim)
331 balanced = redistribute_ring_rows(packed, plan, group, sequence_dim)
332 return tuple(balanced.split(heads, dim=head_dim))