Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / engram / parallel_engram.py: 63%
218 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"""Existing Engram CP/EP execution, sequence alignment and sparse-gradient communication."""
16from __future__ import annotations
18from collections.abc import Callable
19from typing import Any
20import torch
21from torch import nn
22import torch.distributed as dist
23from hyper_parallel.distributed.expert_parallel._tracing import expert_parallel_region
24from hyper_parallel.distributed.expert_parallel.collectives import ep_all_to_all, ep_exchange_counts, ep_split_sizes
27def local_token_mask(token_mask: torch.Tensor | None, hidden_states: torch.Tensor,
28 *, tp_rank: int, tp_size: int) -> torch.Tensor | None:
29 """Match a CP-local token mask to the current TP/SP hidden interval.
31 Args:
32 token_mask: CP-local mask replicated before the embedding boundary.
33 hidden_states: Current TP-local hidden tensor.
34 tp_rank: Local TP rank.
35 tp_size: Number of TP ranks.
37 Returns:
38 Mask aligned to the hidden sequence, or ``None``.
39 """
40 if token_mask is None or token_mask.shape[1] == hidden_states.shape[1]:
41 return token_mask
42 local_length = hidden_states.shape[1]
43 if token_mask.shape[1] != local_length * tp_size:
44 raise ValueError("Engram token mask is incompatible with TP/SP hidden")
45 return token_mask[:, tp_rank * local_length:(tp_rank + 1) * local_length]
48def _all_gather_sequence(value: torch.Tensor, group: Any, group_size: int) -> torch.Tensor:
49 """Gather equal-size sequence chunks and concatenate along dimension one."""
50 gathered = [torch.empty_like(value) for _ in range(group_size)]
51 dist.all_gather(gathered, value.contiguous(), group=group)
52 return torch.cat(gathered, dim=1)
55def aligned_hash_ids(
56 self: Any,
57 hidden_states: torch.Tensor,
58 input_ids: torch.Tensor,
59 segment_starts: torch.Tensor | None,
60 token_mask: torch.Tensor | None = None,
61 *,
62 cp_group: Any = None,
63 cp_rank: int = 0,
64 cp_size: int = 1,
65 tp_rank: int = 0,
66 tp_size: int = 1,
67) -> torch.Tensor:
68 """Hash the local sequence plus the left halo required by n-grams."""
69 cp_local_ids = input_ids
70 if cp_size > 1:
71 input_ids = _all_gather_sequence(input_ids, cp_group, cp_size)
72 if segment_starts is not None:
73 segment_starts = _all_gather_sequence(segment_starts, cp_group, cp_size)
74 if token_mask is not None:
75 token_mask = _all_gather_sequence(token_mask, cp_group, cp_size)
76 local_sequence = hidden_states.shape[1]
77 cp_sequence = cp_local_ids.shape[1]
78 if cp_sequence == local_sequence:
79 sequence_parallel_parts = 1
80 local_tp_rank = 0
81 elif cp_sequence % local_sequence == 0 and cp_sequence // local_sequence == tp_size:
82 sequence_parallel_parts = tp_size
83 local_tp_rank = tp_rank
84 else:
85 raise ValueError(
86 "Engram input_ids length is incompatible with the local hidden sequence: "
87 f"ids={cp_sequence}, hidden={local_sequence}, tp_size={tp_size}"
88 )
89 del sequence_parallel_parts
90 start = cp_rank * cp_sequence + local_tp_rank * local_sequence
91 end = start + local_sequence
92 context_start = max(0, start - self.hash_mapping.max_ngram_size + 1)
93 ids_window = input_ids[:, context_start:end]
94 starts_window = None if segment_starts is None else segment_starts[:, context_start:end]
95 mask_window = None if token_mask is None else token_mask[:, context_start:end]
96 hashes = self.hash_mapping(ids_window, starts_window, mask_window)
97 target_offset = start - context_start
98 return hashes[:, target_offset:target_offset + local_sequence]
101class HostRowsFn(torch.autograd.Function):
102 """Fetch CPU rows and accumulate their backward values as sparse chunks."""
104 @staticmethod
106 def forward(ctx: Any, weight: torch.Tensor, local_ids: torch.Tensor, table: Any) -> torch.Tensor:
107 """Gather touched CPU rows and retain their local IDs for backward.
109 Args:
110 ctx: Autograd context for the row lookup.
111 weight: CPU owner-local table parameter.
112 local_ids: Owner-local row IDs.
113 table: Owner-local Host Engram table.
114 """
115 ctx.table = table
116 ctx.save_for_backward(local_ids)
117 return weight.index_select(0, local_ids)
119 @staticmethod
121 def backward(ctx: Any, grad_rows: torch.Tensor) -> tuple[None, None, None]:
122 """Append touched row gradients without constructing a dense weight grad.
124 Args:
125 ctx: Autograd context for the row lookup.
126 grad_rows: Gradient values for requested rows.
127 """
128 (local_ids,) = ctx.saved_tensors
129 ctx.table.append_rows(local_ids, grad_rows.float().contiguous())
130 return None, None, None
133def host_lookup(table: Any, global_ids: torch.Tensor) -> torch.Tensor:
134 """Deduplicate requests, route by EP owner, and restore input order.
136 Args:
137 table: Owner-local Host Engram table.
138 global_ids: Global Engram row IDs to look up.
139 """
140 if table.rows_per_owner is None or table.global_row_start is None:
141 raise RuntimeError("Host Engram table is not bound")
142 if table.weight.device.type != "cpu" or table.weight.dtype != torch.float32:
143 raise RuntimeError("Host Engram weight must remain CPU FP32")
144 flat_ids = global_ids.reshape(-1).long()
145 unique_ids, inverse = torch.unique(flat_ids, sorted=True, return_inverse=True)
146 table.lookup_requests += flat_ids.numel()
147 table.lookup_unique_ids += unique_ids.numel()
148 invalid_ids = bool(unique_ids.numel() and
149 (unique_ids.min() < 0 or unique_ids.max() >= table.logical_rows))
150 if stage_check(invalid_ids, table.mesh_context):
151 raise IndexError("Engram hash requested a row outside its logical table")
153 if table.ep_size == 1:
154 local_ids = unique_ids.to("cpu")
155 owner_values = HostRowsFn.apply(table.weight, local_ids, table)
156 transfer_values = owner_values.to(table.lookup_compute_dtype)
157 table.host_to_device_bytes += transfer_values.numel() * transfer_values.element_size()
158 unique_values = transfer_values.to(global_ids.device)
159 else:
160 owner = torch.div(unique_ids, table.rows_per_owner, rounding_mode="floor")
161 send_counts_tensor = torch.bincount(owner, minlength=table.ep_size).to(torch.long)
162 count_parts = [torch.empty_like(send_counts_tensor) for _ in range(table.ep_size)]
163 dist.all_gather(count_parts, send_counts_tensor, group=table.ep_group)
164 send_counts = send_counts_tensor.cpu().tolist()
165 recv_counts = torch.stack(count_parts)[:, table.ep_rank].cpu().tolist()
166 # Sorted global IDs already group requests by owner.
167 owned_global_ids = ep_all_to_all(unique_ids, send_counts, recv_counts, table.ep_group)
168 owned_local_ids = (owned_global_ids - table.global_row_start).to("cpu")
169 invalid_owner = bool(owned_local_ids.numel() and (
170 owned_local_ids.min() < 0 or owned_local_ids.max() >= table.rows_per_owner))
171 if stage_check(invalid_owner, table.mesh_context):
172 raise IndexError("Engram EP routing delivered a row to the wrong owner")
173 owner_values = HostRowsFn.apply(table.weight, owned_local_ids, table)
174 transfer_values = owner_values.to(table.lookup_compute_dtype)
175 table.forward_a2a_bytes += unique_ids.numel() * unique_ids.element_size()
176 table.forward_a2a_bytes += transfer_values.numel() * transfer_values.element_size()
177 table.host_to_device_bytes += transfer_values.numel() * transfer_values.element_size()
178 staged_values = transfer_values.to(global_ids.device)
179 unique_values = ep_all_to_all(staged_values, recv_counts, send_counts, table.ep_group)
181 result = unique_values.index_select(0, inverse)
182 return result.view(*global_ids.shape, table.width).to(table.lookup_compute_dtype)
185def _communication_device(mesh) -> torch.device:
186 """Place control and row staging tensors on the collective backend device."""
187 device_type = getattr(mesh, "device_type", "cpu")
188 return torch.device(device_type)
191def gather_sparse_along_axis(coo_cpu: torch.Tensor, axis_mesh: Any, width: int) -> torch.Tensor:
192 """Gather variable COO rows and coalesce them without a dense table grad.
194 Args:
195 coo_cpu: Owner-local sparse COO gradient on CPU.
196 axis_mesh: Mesh axis used to synchronize sparse rows.
197 width: Number of values in each table row.
198 """
199 if axis_mesh is None or axis_mesh.size() == 1:
200 return coo_cpu
201 group = axis_mesh.get_group()
202 device = _communication_device(axis_mesh)
203 coo_cpu = coo_cpu.coalesce()
204 nnz = coo_cpu._nnz() # pylint: disable=protected-access
205 local_count = torch.tensor([nnz], dtype=torch.long, device=device)
206 count_parts = [torch.empty_like(local_count) for _ in range(axis_mesh.size())]
207 dist.all_gather(count_parts, local_count, group=group)
208 counts = [int(part.item()) for part in count_parts]
209 max_count = max(counts)
210 if max_count == 0:
211 return coo_cpu
212 ids = torch.zeros(max_count, dtype=torch.long, device=device)
213 values = torch.zeros((max_count, width), dtype=torch.float32, device=device)
214 if nnz:
215 ids[:nnz] = coo_cpu.indices()[0].to(device)
216 values[:nnz] = coo_cpu.values().to(device)
217 id_parts = [torch.empty_like(ids) for _ in counts]
218 value_parts = [torch.empty_like(values) for _ in counts]
219 dist.all_gather(id_parts, ids, group=group)
220 dist.all_gather(value_parts, values, group=group)
221 gathered_ids = torch.cat([part[:count].cpu() for part, count in zip(id_parts, counts)])
222 gathered_values = torch.cat([part[:count].cpu() for part, count in zip(value_parts, counts)])
223 return torch.sparse_coo_tensor(
224 gathered_ids.unsqueeze(0), gathered_values, coo_cpu.shape,
225 ).coalesce()
228def sparse_sum_same_ep(coo_cpu: torch.Tensor, mesh_context: Any, width: int) -> torch.Tensor:
229 """Sum row contributions over every existing same-owner replica axis.
231 Args:
232 coo_cpu: Owner-local sparse COO gradient on CPU.
233 mesh_context: Parallel mesh and loss-domain configuration.
234 width: Number of values in each table row.
235 """
236 if mesh_context is None or mesh_context.device_mesh is None:
237 return coo_cpu
238 moe = mesh_context.fsdp_moe_mesh
239 if moe is None:
240 for name in ("dp", "cp", "tp"):
241 if name in (mesh_context.device_mesh.mesh_dim_names or ()):
242 coo_cpu = gather_sparse_along_axis(coo_cpu, mesh_context.device_mesh[name], width)
243 else:
244 for name in ("edp_shard", "edp_replicate"):
245 if name in (moe.mesh_dim_names or ()):
246 coo_cpu = gather_sparse_along_axis(coo_cpu, moe[name], width)
247 return coo_cpu
250def stage_reduce_scalar(value: torch.Tensor, mesh_context: Any,
251 op: Any = dist.ReduceOp.SUM) -> torch.Tensor:
252 """Reduce a scalar across the current PP stage in fixed mesh-axis order.
254 Args:
255 value: Scalar value to reduce.
256 mesh_context: Parallel mesh and loss-domain configuration.
257 op: Distributed reduction operation.
258 """
259 if mesh_context is None or mesh_context.device_mesh is None:
260 return value
261 for name in mesh_context.device_mesh.mesh_dim_names or ():
262 axis = mesh_context.device_mesh[name]
263 if axis.size() > 1:
264 dist.all_reduce(value, op=op, group=axis.get_group())
265 return value
268def stage_check(local_bad: bool, mesh_context: Any) -> bool:
269 """Align validation failure across every rank in this PP stage.
271 Args:
272 local_bad: Whether this rank detected an invalid state.
273 mesh_context: Parallel mesh and loss-domain configuration.
274 """
275 mesh = mesh_context.device_mesh if mesh_context is not None else None
276 flag = torch.tensor(int(local_bad), device=_communication_device(mesh))
277 stage_reduce_scalar(flag, mesh_context, dist.ReduceOp.MAX)
278 return bool(flag.item())
281def host_sparse_lookup(hash_ids: torch.Tensor, embedding: Any, *, ep_group: Any,
282 ep_rank: int, ep_size: int, padded_num_embeddings: int) -> torch.Tensor:
283 """Use the already-bound Host row route without applying the device-table route twice."""
284 if (embedding.ep_rank != ep_rank or embedding.ep_size != ep_size or embedding.ep_group is not ep_group
285 or embedding.physical_rows != padded_num_embeddings):
286 raise ValueError("Host lookup must match the table's planned row partition")
287 return embedding(hash_ids)
290class ParallelEngram:
291 """Keep existing parallel execution separate from ordinary Engram fusion."""
293 # The concrete Engram module owns these parameters and local fusion math.
294 embed: nn.Embedding
295 padded_num_embeddings: int
296 _fuse: Callable[[torch.Tensor, torch.Tensor], torch.Tensor]
298 @staticmethod
299 @expert_parallel_region()
300 def _sparse_lookup(
301 hash_ids: torch.Tensor,
302 embedding: nn.Embedding,
303 *,
304 ep_group: Any,
305 ep_rank: int,
306 ep_size: int,
307 padded_num_embeddings: int,
308 ) -> torch.Tensor:
309 """Route requested global rows to their EP owners and restore order."""
310 if padded_num_embeddings % ep_size:
311 raise ValueError(
312 f"Engram padded rows {padded_num_embeddings} are not divisible by ep_size={ep_size}"
313 )
314 num_local_rows = padded_num_embeddings // ep_size
315 row_start = ep_rank * num_local_rows
316 flat_ids = hash_ids.reshape(-1)
317 torch._check_index( # pylint: disable=protected-access
318 ((flat_ids >= 0) & (flat_ids < padded_num_embeddings)).all().item(),
319 lambda: "Engram hash requested a row outside the padded table",
320 )
321 owner = torch.div(flat_ids, num_local_rows, rounding_mode="floor").long()
322 # A fixed-size histogram keeps the peer counts in the graph even when
323 # an owner receives no rows. The exchange only needs one count per peer.
324 local_counts = owner.new_zeros(ep_size).scatter_add_(0, owner, torch.ones_like(owner))
325 received_counts = ep_exchange_counts(local_counts, ep_group)
326 send_counts = ep_split_sizes(local_counts, flat_ids.numel())
327 recv_counts = ep_split_sizes(received_counts)
329 # Ascend ArgSort executes integer inputs on AiCPU. The owner range is
330 # bounded by ep_size, so float32 preserves it exactly and stays on AiCore.
331 sort_indices = torch.argsort(owner.float(), stable=True)
332 sorted_ids = flat_ids.index_select(0, sort_indices)
333 received_ids = ep_all_to_all(sorted_ids, send_counts, recv_counts, ep_group)
334 local_ids = received_ids - row_start
335 torch._check_index( # pylint: disable=protected-access
336 ((local_ids >= 0) & (local_ids < num_local_rows)).all().item(),
337 lambda: "Engram EP routing delivered a row to the wrong owner",
338 )
339 # Call the child module instead of reading ``embedding.weight``
340 # directly. This preserves the FSDP pre/post-forward lifecycle when
341 # the EP table is wrapped independently from the dense Engram gates.
342 values = embedding(local_ids)
343 returned = ep_all_to_all(values, recv_counts, send_counts, ep_group)
344 restored = torch.zeros_like(returned)
345 restored.scatter_add_(
346 0,
347 sort_indices.unsqueeze(1).expand(-1, returned.shape[1]),
348 returned,
349 )
350 return restored.view(*hash_ids.shape, embedding.embedding_dim)
352 def _aligned_hash_ids(
353 self, hidden_states: torch.Tensor, input_ids: torch.Tensor, segment_starts: torch.Tensor | None,
354 token_mask: torch.Tensor | None = None, *, cp_group: Any = None, cp_rank: int = 0, cp_size: int = 1,
355 tp_rank: int = 0, tp_size: int = 1,
356 ) -> torch.Tensor:
357 """Delegate existing sequence alignment while preserving the source method."""
358 return aligned_hash_ids(self, hidden_states, input_ids, segment_starts, token_mask,
359 cp_group=cp_group, cp_rank=cp_rank, cp_size=cp_size,
360 tp_rank=tp_rank, tp_size=tp_size)
362 def parallel_forward(
363 self,
364 hidden_states: torch.Tensor,
365 input_ids: torch.Tensor,
366 segment_starts: torch.Tensor | None = None,
367 token_mask: torch.Tensor | None = None,
368 *,
369 ep_group: Any,
370 ep_rank: int,
371 ep_size: int,
372 cp_group: Any = None,
373 cp_rank: int = 0,
374 cp_size: int = 1,
375 tp_rank: int = 0,
376 tp_size: int = 1,
377 ) -> torch.Tensor:
378 """Run CP/TP sequence alignment and sparse EP lookup.
380 Args:
381 hidden_states: Current decoder hidden rows.
382 input_ids: CP-local token IDs for hash construction.
383 segment_starts: Optional packed sequence boundaries.
384 token_mask: CP-local mask selecting Engram updates.
385 ep_group: Expert-parallel process group.
386 ep_rank: Local expert-parallel rank.
387 ep_size: Expert-parallel degree.
388 cp_group: Context-parallel process group.
389 cp_rank: Local context-parallel rank.
390 cp_size: Context-parallel degree.
391 tp_rank: Local tensor-parallel rank.
392 tp_size: Tensor-parallel degree.
393 """
394 hash_ids = self._aligned_hash_ids(
395 hidden_states,
396 input_ids,
397 segment_starts,
398 token_mask,
399 cp_group=cp_group,
400 cp_rank=cp_rank,
401 cp_size=cp_size,
402 tp_rank=tp_rank,
403 tp_size=tp_size,
404 )
405 embeddings = self._sparse_lookup(
406 hash_ids,
407 self.embed,
408 ep_group=ep_group,
409 ep_rank=ep_rank,
410 ep_size=ep_size,
411 padded_num_embeddings=self.padded_num_embeddings,
412 )
413 fused = self._fuse(hidden_states, embeddings)
414 token_mask = local_token_mask(token_mask, hidden_states, tp_rank=tp_rank, tp_size=tp_size)
415 if token_mask is None:
416 return fused
417 return torch.where(token_mask.to(torch.bool).unsqueeze(-1).unsqueeze(-1), fused, hidden_states)
420class ParallelHostTable:
421 """Own existing EP partition binding without placing it in local row storage."""
423 # The concrete host table owns storage; this base only binds its partition.
424 physical_rows: int
425 width: int
426 weight: nn.Parameter
428 def _init_parallel_state(self) -> None:
429 self.rows_per_owner: int | None = None
430 self.global_row_start: int | None = None
431 self.ep_rank = 0
432 self.ep_size = 1
433 self.ep_group = None
434 self.mesh_context = None
436 def bind_planned_shard(self, *, ep_rank: int, ep_size: int, ep_group: Any = None,
437 compute_dtype: torch.dtype = torch.float32) -> None:
438 """Bind the planner's single EP row shard to its global row interval."""
439 if ep_size < 1 or not 0 <= ep_rank < ep_size or self.physical_rows % ep_size:
440 raise ValueError("Invalid EP row partition")
441 rows = self.physical_rows // ep_size
442 if not self.weight.is_meta or self.weight.dtype != torch.float32:
443 raise ValueError("Planner must leave a meta FP32 Host table")
444 if tuple(self.weight.shape) != (rows, self.width):
445 raise ValueError("Planner did not produce one EP row shard")
446 if ep_size > 1 and ep_group is None:
447 raise ValueError("EP routing requires an explicit process group")
448 self.rows_per_owner = rows
449 self.global_row_start = ep_rank * rows
450 self.ep_rank = ep_rank
451 self.ep_size = ep_size
452 self.ep_group = ep_group
453 self.lookup_compute_dtype = compute_dtype