Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / context_parallel / query_balance.py: 99%
147 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"""Shared document query scheduling and reversible row routes for CP operators."""
17from __future__ import annotations
19from bisect import bisect_right
20from dataclasses import dataclass
21from functools import lru_cache
22from itertools import accumulate
25@dataclass(frozen=True, order=True)
26class QueryTask:
27 """A contiguous query interval in the original document coordinates."""
29 document: int
30 start: int
31 end: int
33 @property
34 def length(self) -> int:
35 """Return the number of real query rows, excluding any synthetic padding."""
36 return self.end - self.start
39def _merge_tasks(tasks: list[QueryTask]) -> tuple[QueryTask, ...]:
40 merged = []
41 for task in sorted(tasks):
42 if merged and merged[-1].document == task.document and merged[-1].end == task.start:
43 merged[-1] = QueryTask(task.document, merged[-1].start, task.end)
44 elif task.length:
45 merged.append(task)
46 return tuple(merged)
49def _zigzag_tasks(lengths: tuple[int, ...], size: int) -> list[list[QueryTask]]:
50 """Assign paired document chunks and evenly distribute their leading remainders."""
51 assignments = [[] for _ in range(size)]
52 remainders = []
53 for document, length in enumerate(lengths):
54 chunk, remainder = divmod(length, 2 * size)
55 if remainder:
56 remainders.append(QueryTask(document, 0, remainder))
57 if chunk:
58 for rank in range(size):
59 for slot in (rank, 2 * size - 1 - rank):
60 start = remainder + slot * chunk
61 assignments[rank].append(QueryTask(document, start, start + chunk))
62 # All ranks already own equally many paired rows. Distribute the real
63 # remainder rows evenly without inserting tokens into any document.
64 capacity = sum(task.length for task in remainders) // size
65 rank, used = 0, 0
66 for task in remainders:
67 start = task.start
68 while start < task.end:
69 if used == capacity:
70 rank += 1
71 used = 0
72 end = min(task.end, start + capacity - used)
73 assignments[rank].append(QueryTask(task.document, start, end))
74 used += end - start
75 start = end
76 return assignments
79@lru_cache(maxsize=128)
80def query_task_plan(
81 lengths: tuple[int, ...], size: int, load_balance: str = "none",
82) -> tuple[tuple[QueryTask, ...], ...]:
83 """Assign document-local queries with bounded worker capacity.
85 Args:
86 lengths: Positive global document lengths in packed order, shared by all ranks.
87 size: Number of workers; total tokens must divide size.
88 load_balance: Contiguous 'none' or per-document 'zigzag'.
90 Returns:
91 Sorted disjoint query intervals per worker. Zigzag keeps equal row counts.
92 """
93 if (not isinstance(size, int) or isinstance(size, bool) or size < 1 or not lengths
94 or any(not isinstance(length, int) or isinstance(length, bool) or length < 1 for length in lengths)
95 or sum(lengths) % size):
96 raise ValueError("query plans require positive lengths and equal contiguous source shards")
97 if load_balance not in ("none", "zigzag"):
98 raise ValueError("load_balance must be none or zigzag")
99 local = sum(lengths) // size
100 if load_balance == "none":
101 boundaries = (0, *accumulate(lengths))
102 return tuple(tuple(QueryTask(document, max(rank * local, begin) - begin,
103 min((rank + 1) * local, end) - begin)
104 for document, (begin, end) in enumerate(zip(boundaries, boundaries[1:]))
105 if max(rank * local, begin) < min((rank + 1) * local, end))
106 for rank in range(size))
107 assignments = _zigzag_tasks(lengths, size)
108 return tuple(_merge_tasks(tasks) for tasks in assignments)
111def _distribute_leading_remainder(assignments, document, workers, remainder):
112 """Spread a document's leading remainder over only its participating ranks."""
113 base, extra = divmod(remainder, len(workers))
114 start = 0
115 for index, worker in enumerate(workers):
116 count = base + (index < extra)
117 if count:
118 assignments[worker].append(QueryTask(document, start, start + count))
119 start += count
122def _subring_zigzag(assignments, document, length, workers):
123 """Pair causal head/tail chunks across the ranks intersecting one document."""
124 chunk, remainder = divmod(length, 2 * len(workers))
125 _distribute_leading_remainder(assignments, document, workers, remainder)
126 for index, worker in enumerate(workers):
127 for slot in (index, 2 * len(workers) - 1 - index):
128 start = remainder + slot * chunk
129 if chunk:
130 assignments[worker].append(QueryTask(document, start, start + chunk))
133@lru_cache(maxsize=128)
134def query_task_plan_in_document_rings(
135 lengths: tuple[int, ...], size: int, load_balance: str = "none",
136) -> tuple[tuple[QueryTask, ...], ...]:
137 """Balance each document only among CP ranks that intersect that document.
139 Unlike ``query_task_plan``, this planner preserves the document's contiguous
140 source-owner subring. It is used with document-pruned KV transport, so no
141 query is moved to a rank outside the document's active ring.
142 """
143 if (not isinstance(size, int) or isinstance(size, bool) or size < 1
144 or not lengths or any(not isinstance(length, int) or isinstance(length, bool) or length < 1
145 for length in lengths)
146 or sum(lengths) % size):
147 raise ValueError("document subrings require positive lengths and equal contiguous source shards")
148 if load_balance not in ("none", "zigzag"):
149 raise ValueError("load_balance must be none or zigzag")
150 local = sum(lengths) // size
152 assignments = [[] for _ in range(size)]
153 boundaries = (0, *accumulate(lengths))
154 for document, (begin, end) in enumerate(zip(boundaries, boundaries[1:])):
155 first = begin // local
156 last = (end - 1) // local
157 workers = tuple(range(first, last + 1))
158 length = end - begin
159 if load_balance == "none":
160 for worker in workers:
161 left = max(begin, worker * local) - begin
162 right = min(end, (worker + 1) * local) - begin
163 assignments[worker].append(QueryTask(document, left, right))
164 elif load_balance == "zigzag":
165 _subring_zigzag(assignments, document, length, workers)
166 return tuple(_merge_tasks(tasks) for tasks in assignments)
169def _send_ranges(tasks: tuple, boundaries: tuple[int, ...], owner: int, local: int) -> tuple:
170 """Find only tasks intersecting this owner in each sorted worker assignment."""
171 first, last = owner * local, (owner + 1) * local
172 start = bisect_right(tasks, first, key=lambda task: boundaries[task.document] + task.end)
173 result = []
174 for index in range(start, len(tasks)):
175 task = tasks[index]
176 begin, end = boundaries[task.document] + task.start, boundaries[task.document] + task.end
177 if begin >= last:
178 break
179 begin, end = max(first, begin), min(last, end)
180 result.append((begin - first, end - begin))
181 return tuple(result)
184def _receive_ranges(tasks: tuple, boundaries: tuple[int, ...], size: int, local: int) -> tuple:
185 """Index a worker's tasks by owner once, retaining its original packed offsets."""
186 owners, cursor = [[] for _ in range(size)], 0
187 for task in tasks:
188 begin, end = boundaries[task.document] + task.start, boundaries[task.document] + task.end
189 for owner in range(begin // local, (end - 1) // local + 1):
190 first, last = max(begin, owner * local), min(end, (owner + 1) * local)
191 owners[owner].append((first - owner * local, cursor + first - begin, last - first))
192 cursor += task.length
193 return tuple(tuple(rows) for rows in owners)
196@dataclass(frozen=True)
197class QueryRoute:
198 """Device-independent row ordering and matching variable collective splits."""
200 input_splits: tuple[int, ...]
201 output_splits: tuple[int, ...]
202 send_rows: tuple[int, ...]
203 receive_rows: tuple[int, ...]
204 local_sources: tuple[int, ...]
205 local_targets: tuple[int, ...]
206 query_count: int
209@lru_cache(maxsize=128)
210def query_route(assignments: tuple, lengths: tuple[int, ...], rank: int) -> QueryRoute:
211 """Build a reversible owner-to-worker row route with local rows bypassing communication."""
212 size = len(assignments)
213 boundaries, local = (0, *accumulate(lengths)), sum(lengths) // size
214 if not 0 <= rank < size:
215 raise ValueError("rank must belong to the task plan")
216 receives = _receive_ranges(assignments[rank], boundaries, size, local)
217 sends = tuple(_send_ranges(tasks, boundaries, rank, local) if peer != rank else ()
218 for peer, tasks in enumerate(assignments))
219 return query_route_from_ranges(assignments[rank], rank, sends, receives)
222def query_route_from_ranges(tasks: tuple, rank: int,
223 sends: tuple, receives: tuple) -> QueryRoute:
224 """Preserve peer ordering and local bypass for either task-planning path."""
225 send_rows, receive_rows, inputs, outputs = [], [], [], []
226 for peer, sent in enumerate(sends):
227 sent = sent if peer != rank else ()
228 received = receives[peer] if peer != rank else ()
229 inputs.append(sum(count for _, count in sent))
230 outputs.append(sum(count for _, _, count in received))
231 send_rows.extend(row for start, count in sent for row in range(start, start + count))
232 receive_rows.extend(row for _, start, count in received for row in range(start, start + count))
233 sources = tuple(row for start, _, count in receives[rank] for row in range(start, start + count))
234 targets = tuple(row for _, start, count in receives[rank] for row in range(start, start + count))
235 return QueryRoute(tuple(inputs), tuple(outputs),
236 tuple(send_rows), tuple(receive_rows), sources, targets,
237 sum(task.length for task in tasks))