Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / engram / engram.py: 97%

144 statements  

« 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"""Engram parameter ownership, device lookup and local fusion.""" 

16from __future__ import annotations 

17 

18from collections.abc import Mapping 

19from math import isfinite 

20from typing import Any 

21 

22import torch 

23from torch import nn 

24from torch.nn import functional as F 

25 

26from hyper_parallel.core.dtensor.dtensor import DTensor 

27from hyper_parallel.core.dtensor.placement_types import Replicate, Shard 

28from hyper_parallel.distributed.module_binding import ParallelBinding, ParallelModuleSpec 

29from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec 

30 

31from .host_engram_table import HostEngramTable 

32from .ngram_hash_mapping import NgramHashMapping 

33from .parallel_engram import ParallelEngram, local_token_mask 

34 

35 

36def engram_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec: 

37 """Own replicated fusion weights and EP rows without splitting the fusion projection.""" 

38 del module_fqn, member 

39 replicated = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes} 

40 params = {name: dict(replicated) for name, _ in module.named_parameters()} 

41 if context.axis_sizes["ep"] > 1: 

42 params["embed.weight"]["ep"] = Shard(0) 

43 return ModuleShardingSpec(params=params, in_src={}, in_dst={}, is_boundary=False) 

44 

45 

46def validate_engram_layout(*, module: nn.Module, sharding: Any, context: Any) -> None: 

47 """Reject unsupported row partitions and fusion layouts before binding communication.""" 

48 expected = engram_sharding(module=module, module_fqn="", member=None, context=context) 

49 if set(sharding.params) != set(expected.params): 

50 raise ValueError("Engram requires replicated fusion weights and contiguous EP table rows") 

51 for name, required in expected.params.items(): 

52 actual = sharding.params[name] 

53 if any(actual.get(axis, Replicate()) != required.get(axis, Replicate()) 

54 for axis in set(actual) | set(required)): 

55 raise ValueError(f"Engram requires replicated fusion weights and contiguous EP table rows: {name}") 

56 if module.padded_num_embeddings % context.axis_sizes["ep"]: 

57 raise ValueError("Engram physical table rows must be padded to an EP-size multiple") 

58 

59 

60class _LocalRowEmbedding(nn.Embedding): 

61 """Consume owner-local row indices while preserving ordinary child/FSDP hooks.""" 

62 

63 @classmethod 

64 

65 def adopt(cls, source: nn.Embedding) -> "_LocalRowEmbedding": 

66 """Preserve the source Parameter identity without initializing or copying weights.""" 

67 if source.padding_idx is not None or source.max_norm is not None or source.scale_grad_by_freq or source.sparse: 

68 raise ValueError("Engram requires an unpadded dense embedding without in-place row normalization") 

69 if isinstance(source, cls): 

70 return source 

71 result = cls(source.num_embeddings, source.embedding_dim, _weight=source.weight, 

72 _freeze=not source.weight.requires_grad) 

73 result.weight = source.weight 

74 result.training = source.training 

75 return result 

76 

77 def forward(self, input: torch.Tensor) -> torch.Tensor: # pylint: disable=redefined-builtin 

78 """Look up already-routed local rows without a second global-vocabulary redistribution.""" 

79 weight = self.weight.to_local() if isinstance(self.weight, DTensor) else self.weight 

80 return F.embedding(input, weight) 

81 

82 

83class EngramModule(ParallelEngram, nn.Module): 

84 """Ordinary Engram parameter ownership and local fusion with separate parallel execution.""" 

85 

86 def __init__( 

87 self, 

88 *, 

89 module: nn.Module | None = None, 

90 module_fqn: str = "", 

91 context: Mapping[str, Any] | None = None, 

92 config: Any = None, 

93 ) -> None: 

94 """Reuse a source Engram module's parameters and hash mapping.""" 

95 super().__init__() 

96 del module_fqn, context 

97 if (module is None) == (config is None): 

98 raise ValueError("provide exactly one of config or module") 

99 if config is not None: 

100 self._init_from_config(config) 

101 return 

102 required = ("hash_mapping", "embed", "wkv", "q_weight", "k_weight") 

103 missing = [name for name in required if not hasattr(module, name)] 

104 if missing: 

105 raise TypeError(f"Engram source is missing required attributes: {missing}") 

106 self.hash_mapping = module.hash_mapping 

107 self.embed = _LocalRowEmbedding.adopt(module.embed) if isinstance(module.embed, nn.Embedding) else module.embed 

108 self.wkv = module.wkv 

109 self.q_weight = module.q_weight 

110 self.k_weight = module.k_weight 

111 self.layer_id = int(module.layer_id) 

112 self.hidden_size = int(module.hidden_size) 

113 self.hc_mult = int(module.hc_mult) 

114 self.eps = float(module.eps) 

115 self.clamp_value = float(module.clamp_value) 

116 self.logical_num_embeddings = int(module.logical_num_embeddings) 

117 self.padded_num_embeddings = int(module.padded_num_embeddings) 

118 self.train(module.training) 

119 

120 def parallel_module_spec(self) -> ParallelModuleSpec: 

121 """Borrow existing job groups; Engram owns its sparse row transport and hash halo.""" 

122 return ParallelModuleSpec( 

123 "engram.rows", 

124 "mesh", 

125 {"forward": ("hidden_states", "input_ids", "segment_starts", "token_mask")}, 

126 validate=validate_engram_layout, 

127 ) 

128 

129 def bind_parallel(self, binding: ParallelBinding) -> None: 

130 """Record job-owned EP/CP/TP resources without constructing additional groups.""" 

131 mesh = binding.mesh_binding.mesh_context 

132 sizes = {axis: int(getattr(mesh, f"{axis}_size", 1)) for axis in ("ep", "cp", "tp")} 

133 state = {} 

134 for axis in ("ep", "cp"): 

135 axis_mesh = binding.mesh_binding.axis_mesh(axis) if sizes[axis] > 1 else None 

136 state.update( 

137 { 

138 f"{axis}_size": sizes[axis], 

139 f"{axis}_rank": axis_mesh.get_local_rank() if axis_mesh is not None else 0, 

140 f"{axis}_group": axis_mesh.get_group() if axis_mesh is not None else None, 

141 } 

142 ) 

143 state.update( 

144 tp_size=sizes["tp"] if getattr(mesh, "sequence_parallel", False) else 1, 

145 tp_rank=int(getattr(mesh, "tp_rank", 0)), 

146 ) 

147 self._parallel_state = state 

148 

149 def _init_from_config(self, config: Any) -> None: 

150 """Validate hash assets and allocate local fusion parameters for direct construction.""" 

151 for name in ("hidden_size", "hc_mult", "embedding_dim"): 

152 value = getattr(config, name) 

153 if isinstance(value, bool) or not isinstance(value, int) or value <= 0: 

154 raise ValueError(f"{name} must be a positive integer") 

155 if isinstance(config.layer_id, bool) or not isinstance(config.layer_id, int): 

156 raise ValueError("layer_id must be an integer") 

157 for name in ("eps", "clamp_value"): 

158 value = getattr(config, name) 

159 if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value) or value <= 0: 

160 raise ValueError(f"{name} must be finite and positive") 

161 self.layer_id, self.hidden_size, self.hc_mult = config.layer_id, config.hidden_size, config.hc_mult 

162 self.eps, self.clamp_value = config.eps, config.clamp_value 

163 self._init_table_from_config(config) 

164 

165 def _init_table_from_config(self, config: Any) -> None: 

166 """Validate the physical row budget before allocating the table and fusion projections.""" 

167 self.hash_mapping = NgramHashMapping(config.assets, config.layer_id) 

168 self.logical_num_embeddings = self.hash_mapping.logical_num_embeddings 

169 rows = config.padded_num_embeddings 

170 if rows is None: 

171 rows = self.logical_num_embeddings 

172 if isinstance(rows, bool) or not isinstance(rows, int) or rows < self.logical_num_embeddings: 

173 raise ValueError("padded_num_embeddings must cover all logical hash rows") 

174 self.padded_num_embeddings = rows 

175 columns = (self.hash_mapping.max_ngram_size - 1) * self.hash_mapping.num_heads 

176 self.embed = self._create_embedding(self.padded_num_embeddings, config.embedding_dim) 

177 self.wkv = nn.Linear(columns * config.embedding_dim, (config.hc_mult + 1) * config.hidden_size, bias=False) 

178 self.q_weight = nn.Parameter(torch.ones(config.hc_mult, config.hidden_size)) 

179 self.k_weight = nn.Parameter(torch.ones(config.hc_mult, config.hidden_size)) 

180 

181 def _create_embedding(self, rows: int, width: int) -> nn.Embedding: 

182 """Allocate the device-table representation for direct construction.""" 

183 return _LocalRowEmbedding(rows, width) 

184 

185 def reset_parameters(self) -> None: 

186 """Initialize owned query/key scales after materialization.""" 

187 nn.init.ones_(self.q_weight) 

188 nn.init.ones_(self.k_weight) 

189 

190 def make_transforms(self) -> list: 

191 """Keep source parameter names and layouts unchanged.""" 

192 return [] 

193 

194 def checkpoint_logical_shapes(self) -> dict[str, tuple[int, ...]]: 

195 """Return the logical embedding shape for checkpoint loading and checking.""" 

196 return {"embed.weight": (self.logical_num_embeddings, int(self.embed.weight.shape[1]))} 

197 

198 def _fuse(self, hidden_states: torch.Tensor, embeddings: torch.Tensor) -> torch.Tensor: 

199 """Apply the exact V4.1 WKV projection and signed-root gate.""" 

200 key_value = self.wkv(embeddings.flatten(start_dim=-2)) 

201 key, value = key_value.split( 

202 [self.hc_mult * self.hidden_size, self.hidden_size], dim=-1 

203 ) 

204 key = key.float().unflatten(-1, (self.hc_mult, self.hidden_size)) 

205 hidden_fp32 = hidden_states.float() 

206 weight = self.q_weight.float() * self.k_weight.float() 

207 reciprocal_std = torch.rsqrt(hidden_fp32.square().mean(-1) + self.eps) 

208 reciprocal_std = reciprocal_std * torch.rsqrt(key.square().mean(-1) + self.eps) 

209 dot = (hidden_fp32 * weight * key).sum(-1) 

210 dot = dot * reciprocal_std * self.hidden_size**-0.5 

211 root = dot.abs().clamp_min(self.clamp_value).sqrt() 

212 signed_root = torch.where(dot < 0, -root, root) 

213 gate = torch.sigmoid(signed_root) 

214 return ( 

215 hidden_fp32 + gate.unsqueeze(-1) * value.float().unsqueeze(-2) 

216 ).to(hidden_states.dtype) 

217 

218 

219 def forward( 

220 self, 

221 hidden_states: torch.Tensor, 

222 input_ids: torch.Tensor, 

223 segment_starts: torch.Tensor | None = None, 

224 token_mask: torch.Tensor | None = None, 

225 ) -> torch.Tensor: 

226 """Run owned hash alignment, sparse table lookup and residual fusion. 

227 

228 Args: 

229 hidden_states: Current decoder hidden rows. 

230 input_ids: Local token IDs for hash lookup. 

231 segment_starts: Optional packed sequence boundaries. 

232 token_mask: Optional mask selecting Engram updates. 

233 """ 

234 state = getattr(self, "_parallel_state", {}) 

235 if state.get("ep_size", 1) > 1 and not isinstance(self.embed, HostEngramTable): 

236 return self.parallel_forward( 

237 hidden_states, input_ids, segment_starts, token_mask, 

238 ep_group=state["ep_group"], ep_rank=state["ep_rank"], ep_size=state["ep_size"], 

239 **{key: value for key, value in state.items() if not key.startswith("ep_")}, 

240 ) 

241 sequence = {key: value for key, value in state.items() if not key.startswith("ep_")} 

242 hash_ids = self._aligned_hash_ids(hidden_states, input_ids, segment_starts, token_mask, **sequence) 

243 fused = self._fuse(hidden_states, self.embed(hash_ids)) 

244 token_mask = local_token_mask( 

245 token_mask, hidden_states, tp_rank=state.get("tp_rank", 0), tp_size=state.get("tp_size", 1) 

246 ) 

247 if token_mask is None: 

248 return fused 

249 return torch.where(token_mask.to(torch.bool).unsqueeze(-1).unsqueeze(-1), fused, hidden_states)