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

129 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"""Resolve and materialize only the Host rows owned by this EP rank.""" 

16 

17import hashlib 

18import json 

19from collections.abc import Callable, Mapping 

20from pathlib import Path 

21from typing import Any 

22 

23import torch 

24from safetensors import safe_open 

25from torch import nn 

26 

27from hyper_parallel.components.checkpoint.weight_conversion import ( 

28 WeightConverter, 

29 WeightRenaming, 

30 rename_source_key, 

31) 

32from hyper_parallel.components.checkpoint.load_groups import ( 

33 base_weights_mapping, 

34 build_load_targets, 

35 resolve_checkpoint_index, 

36) 

37from hyper_parallel.components.modules.engram.host_engram_table import HostEngramTable 

38from hyper_parallel.components.checkpoint.quantized_hf_storage import build_quantized_hf_reader 

39from hyper_parallel.models.external_state import ExternalLoadContext 

40 

41 

42def _row_manifest(checkpoint_index: Any) -> tuple[Path, dict[str, Any]]: 

43 """Read optional logical-table to physical-safetensors row mapping.""" 

44 root = next(iter(checkpoint_index.files_by_key.values())).parent 

45 path = root / "engram_host_rows.json" 

46 if not path.is_file(): 

47 return root, {} 

48 payload = json.loads(path.read_text(encoding="utf-8")) 

49 if payload.get("format_version") != 1 or not isinstance(payload.get("tables"), dict): 

50 raise ValueError("Invalid Engram Host row manifest") 

51 return root, payload["tables"] 

52 

53 

54def _read_manifest_rows(root: Path, source_key: str, spec: dict[str, Any], 

55 table: HostEngramTable) -> torch.Tensor: 

56 """Validate complete physical row coverage and read only this owner.""" 

57 if spec.get("shape") != [table.physical_rows, table.width]: 

58 raise ValueError(f"Host Engram manifest shape mismatch: {source_key}") 

59 fragments = spec.get("fragments") 

60 if not isinstance(fragments, list) or not fragments: 

61 raise ValueError(f"Host Engram manifest has no row fragments: {source_key}") 

62 rows = torch.empty((table.rows_per_owner, table.width), dtype=torch.float32) 

63 owner_start = table.global_row_start 

64 owner_end = owner_start + table.rows_per_owner 

65 cursor = 0 

66 for fragment in sorted(fragments, key=lambda item: item["start"]): 

67 start, length = int(fragment["start"]), int(fragment["rows"]) 

68 end = start + length 

69 if start != cursor or length <= 0: 

70 raise ValueError(f"Host Engram manifest row gap or overlap: {source_key}") 

71 cursor = end 

72 left, right = max(start, owner_start), min(end, owner_end) 

73 if left >= right: 

74 continue 

75 path = (root / fragment["file"]).resolve() 

76 if not path.is_relative_to(root.resolve()) or path.suffix != ".safetensors": 

77 raise ValueError(f"Host Engram manifest has invalid fragment path: {source_key}") 

78 with safe_open(str(path), framework="pt", device="cpu") as source: 

79 tensor_slice = source.get_slice(fragment["key"]) 

80 if tuple(tensor_slice.get_shape()) != (length, table.width): 

81 raise ValueError(f"Host Engram manifest fragment shape mismatch: {source_key}") 

82 part = tensor_slice[left - start:right - start] 

83 if part.dtype != torch.float32: 

84 raise ValueError(f"Host Engram manifest fragment dtype mismatch: {source_key}") 

85 rows[left - owner_start:right - owner_start] = part 

86 if cursor != table.physical_rows: 

87 raise ValueError(f"Host Engram manifest row coverage incomplete: {source_key}") 

88 return rows 

89 

90 

91def _host_source_keys(model: nn.Module, checkpoint_index: Any, 

92 manifest: dict[str, Any], weights_mapping: Any, 

93 targets: frozenset[str]) -> dict[str, str]: 

94 """Resolve one sliceable source tensor for each Host target FQN.""" 

95 replacement_mapping = getattr(model, "_hp_replacement_weight_conversions", None) 

96 mapping = base_weights_mapping(weights_mapping or [], replacement_mapping or []) 

97 renamings = [item for item in mapping if isinstance(item, WeightRenaming)] 

98 converters = [item for item in mapping if isinstance(item, WeightConverter)] 

99 all_targets = build_load_targets(model) 

100 found: dict[str, str] = {} 

101 for source_key in sorted(set(checkpoint_index.keys()) | manifest.keys()): 

102 target, source_pattern = rename_source_key( 

103 source_key, renamings, converters, getattr(model, "base_model_prefix", None), 

104 meta_state_dict=all_targets, 

105 ) 

106 if target not in targets and source_key in targets: 

107 target, source_pattern = rename_source_key( 

108 source_key, [], [], getattr(model, "base_model_prefix", None), 

109 meta_state_dict=all_targets, 

110 ) 

111 if target not in targets: 

112 continue 

113 if source_pattern is not None: 

114 raise ValueError(f"Host Engram source conversion cannot be sliced: {source_key}") 

115 if target in found: 

116 raise ValueError(f"Multiple Host Engram source keys map to {target}") 

117 found[target] = source_key 

118 missing = targets - found.keys() 

119 if missing: 

120 raise KeyError(f"Missing Host Engram source key for {sorted(missing)}") 

121 return found 

122 

123 

124def _seed_owner_rows(fqn: str, table: HostEngramTable) -> torch.Tensor: 

125 """Initialize each owner row independently of EP replica placement.""" 

126 rows = torch.empty((table.rows_per_owner, table.width), dtype=torch.float32) 

127 generator = torch.Generator(device="cpu") 

128 layer_seed = int.from_bytes(hashlib.sha256(fqn.encode()).digest()[:8], "little") 

129 for local_row in range(table.rows_per_owner): 

130 generator.manual_seed((1729 + layer_seed + table.global_row_start + local_row) % (2**63 - 1)) 

131 rows[local_row] = torch.randn(table.width, generator=generator) 

132 return rows 

133 

134 

135def _read_source_owner_rows(source_key: str, table: HostEngramTable, 

136 shape: tuple[int, ...], read_rows: Callable[[int, int], torch.Tensor]) -> torch.Tensor: 

137 """Read the owner's logical rows and zero any physical tail padding.""" 

138 if (len(shape) != 2 or shape[1] != table.width 

139 or shape[0] not in (table.logical_rows, table.physical_rows)): 

140 raise ValueError(f"Host Engram source shape mismatch: {source_key}") 

141 count = max(0, min(table.rows_per_owner, table.logical_rows - table.global_row_start)) 

142 if count == table.rows_per_owner: 

143 return read_rows(table.global_row_start, count).float() 

144 rows = torch.zeros((table.rows_per_owner, table.width), dtype=torch.float32) 

145 if count: 

146 rows[:count] = read_rows(table.global_row_start, count).float() 

147 return rows 

148 

149 

150def materialize_owner_rows(model: nn.Module, tables: Mapping[str, HostEngramTable], 

151 context: ExternalLoadContext) -> frozenset[str]: 

152 """Install each owner's CPU rows into its existing parameter object. 

153 

154 Args: 

155 model: Model whose source key mappings are resolved. 

156 tables: Exact named Host tables whose weights are replaced in place. 

157 context: Source path and optional mapping for pretrained loading. 

158 

159 Returns: 

160 Source keys consumed by the Host tables, or an empty set for initialization. 

161 """ 

162 source_keys = set() 

163 index = None 

164 source_by_target = {} 

165 manifest_root = None 

166 manifest = {} 

167 quantized_reader = None 

168 if context.load_base_model and tables: 

169 index = resolve_checkpoint_index(context.pretrained_path) 

170 manifest_root, manifest = _row_manifest(index) 

171 quantized_reader = build_quantized_hf_reader(manifest_root) 

172 targets = frozenset(f"{fqn}.weight" for fqn in tables) 

173 source_by_target = _host_source_keys( 

174 model, index, manifest, context.weights_mapping, targets, 

175 ) 

176 for fqn, table in tables.items(): 

177 target = f"{fqn}.weight" 

178 if index is None: 

179 rows = _seed_owner_rows(fqn, table) 

180 else: 

181 source_key = source_by_target[target] 

182 if source_key in manifest: 

183 rows = _read_manifest_rows(manifest_root, source_key, manifest[source_key], table) 

184 elif quantized_reader is not None: 

185 metadata = quantized_reader.load_metadata().state_dict_metadata[source_key] 

186 rows = _read_source_owner_rows( 

187 source_key, table, tuple(metadata.size), 

188 lambda start, count, source_key=source_key, width=table.width, reader=quantized_reader: 

189 reader.read_region(source_key, (start, 0), (count, width)), 

190 ) 

191 else: 

192 with safe_open(str(index.files_by_key[source_key]), framework="pt", device="cpu") as source: 

193 tensor_slice = source.get_slice(source_key) 

194 if tensor_slice.get_dtype() not in ("BF16", "F32"): 

195 raise ValueError(f"Host Engram source requires BF16/FP32 weights: {target}") 

196 rows = _read_source_owner_rows( 

197 source_key, table, tuple(tensor_slice.get_shape()), 

198 lambda start, count, tensor_slice=tensor_slice: tensor_slice[start:start + count], 

199 ) 

200 source_keys.add(source_key) 

201 if rows.dtype != torch.float32 or tuple(rows.shape) != tuple(table.weight.shape): 

202 raise ValueError(f"Host Engram source dtype or local shape mismatch: {target}") 

203 torch.utils.swap_tensors(table.weight, nn.Parameter(rows.contiguous())) 

204 table.weight._is_hf_initialized = True # pylint: disable=W0212 

205 return frozenset(source_keys)