Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / engram / host_engram_table.py: 80%
87 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"""Owner-local FP32 Engram parameters and one-step sparse gradient storage."""
17from __future__ import annotations
19import torch
20from torch import nn
22from .parallel_engram import ParallelHostTable, host_lookup
25class HostEngramTable(ParallelHostTable, nn.Module):
26 """Keep one EP owner's rows on CPU and stage only touched rows on device."""
28 def __init__(self, *, source_weight: nn.Parameter, logical_rows: int,
29 max_pending_entries: int = 1000000,
30 max_sparse_rows_per_step: int = 1000000) -> None:
31 """Validate the full meta weight and configure sparse entry budgets."""
32 super().__init__()
33 if source_weight.ndim != 2:
34 raise ValueError("Host Engram source weight must be a matrix")
35 physical_rows, width = source_weight.shape
36 if not 0 < logical_rows <= physical_rows or width <= 0:
37 raise ValueError("Invalid Engram table shape")
38 if not source_weight.is_meta or source_weight.dtype != torch.float32:
39 raise ValueError("Host Engram replacement requires a meta FP32 weight")
40 if max_pending_entries <= 0 or max_sparse_rows_per_step <= 0:
41 raise ValueError("Host Engram sparse budgets must be positive")
42 self.weight = source_weight
43 self.logical_rows = logical_rows
44 self.physical_rows = physical_rows
45 self.width = width
46 self.max_pending_entries = max_pending_entries
47 self.max_sparse_rows_per_step = max_sparse_rows_per_step
48 self._init_parallel_state()
49 self.lookup_compute_dtype = torch.float32
50 self.pending_chunks: list[tuple[torch.Tensor, torch.Tensor]] = []
51 self.pending: torch.Tensor | None = None
52 self.pending_error: str | None = None
53 self.lookup_requests = 0
54 self.lookup_unique_ids = 0
55 self.forward_a2a_bytes = 0
56 self.host_to_device_bytes = 0
57 self.max_synced_nnz = 0
58 self.coalesce_seconds = 0.0
61 def _apply(self, fn, recurse=True):
62 """Keep the CPU parameter outside model-wide device and dtype changes."""
63 weight = self._parameters.pop("weight")
64 try:
65 return super()._apply(fn, recurse=recurse)
66 finally:
67 self.register_parameter("weight", weight)
69 def append_rows(self, local_ids: torch.Tensor, grad_rows: torch.Tensor) -> None:
70 """Append owner-local CPU gradients without making a dense table grad.
72 Args:
73 local_ids: Owner-local row IDs.
74 grad_rows: Gradient values for requested rows.
75 """
76 if self.rows_per_owner is None:
77 raise RuntimeError("Host Engram table is not bound")
78 if local_ids.device.type != "cpu" or grad_rows.device.type != "cpu":
79 raise ValueError("Host Engram pending gradients must reside on CPU")
80 if local_ids.dtype != torch.long or grad_rows.dtype != torch.float32:
81 raise ValueError("Host Engram pending gradients require int64 IDs and FP32 values")
82 if tuple(grad_rows.shape) != (local_ids.numel(), self.width):
83 raise ValueError("Host Engram pending gradient shape mismatch")
84 if local_ids.numel() and (local_ids.min() < 0 or local_ids.max() >= self.rows_per_owner):
85 raise IndexError("Host Engram pending row is outside the owner shard")
86 entries = sum(ids.numel() for ids, _ in self.pending_chunks) + local_ids.numel()
87 if entries > self.max_pending_entries:
88 # Autograd backward may run before other EP ranks have finished their
89 # collectives. Report the failure at the aligned optimizer-step gate.
90 self.pending_error = "Host Engram pending entry budget exceeded"
91 return
92 self.pending_chunks.append((local_ids.detach(), grad_rows.detach()))
94 def coalesce_pending(self) -> torch.Tensor:
95 """Combine microbatches and repeated rows into one sparse CPU tensor."""
96 if self.rows_per_owner is None:
97 raise RuntimeError("Host Engram table is not bound")
98 if self.pending_error is not None:
99 raise ValueError(self.pending_error)
100 ids = (torch.cat([chunk[0] for chunk in self.pending_chunks]) if self.pending_chunks
101 else torch.empty(0, dtype=torch.long))
102 values = (torch.cat([chunk[1] for chunk in self.pending_chunks]) if self.pending_chunks
103 else torch.empty((0, self.width), dtype=torch.float32))
104 result = torch.sparse_coo_tensor(ids.unsqueeze(0), values,
105 (self.rows_per_owner, self.width)).coalesce()
106 if result._nnz() > self.max_sparse_rows_per_step: # pylint: disable=protected-access
107 raise ValueError("Host Engram unique sparse row budget exceeded")
108 if not torch.isfinite(result.values()).all():
109 raise ValueError("Host Engram gradient contains non-finite values")
110 return result
112 def install_grad(self) -> None:
113 """Expose only the prepared sparse gradient to SparseAdam."""
114 if self.pending is None:
115 raise RuntimeError("Host Engram sparse gradient has not been prepared")
116 self.weight.grad = self.pending if self.pending._nnz() else None # pylint: disable=protected-access
118 def clear_step(self) -> None:
119 """Release sparse gradients after the optimizer step."""
120 self.weight.grad = None
121 self.pending = None
122 self.pending_chunks.clear()
123 self.pending_error = None
124 self.lookup_requests = 0
125 self.lookup_unique_ids = 0
126 self.forward_a2a_bytes = 0
127 self.host_to_device_bytes = 0
128 self.max_synced_nnz = 0
129 self.coalesce_seconds = 0.0
131 def reset_parameters(self) -> None:
132 """Preserve already materialized CPU rows during model initialization."""
134 def make_transforms(self) -> list:
135 """Declare that this member keeps parameter names and layouts unchanged.
137 Returns:
138 An empty converter list, matching members whose initialization is
139 fully owned by ``reset_parameters``.
140 """
141 return []
143 def forward(self, global_ids: torch.Tensor) -> torch.Tensor:
144 """Look up global row IDs through the owner-local CPU table.
146 Args:
147 global_ids: Global Engram row IDs to look up.
148 """
149 return host_lookup(self, global_ids)