Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / tools / dryrun / examples / deepseek_v41.py: 98%

99 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"""DeepSeek V4.1 text-model recipe for logical memory simulation.""" 

16 

17from types import MethodType 

18from typing import Any, Optional 

19 

20import torch 

21from torch.nn import functional 

22from torch.utils.checkpoint import checkpoint 

23from transformers.modeling_outputs import CausalLMOutputWithPast 

24 

25from hyper_parallel.components.modules.engram import EngramModule 

26from hyper_parallel.tools.dryrun.patches.models.moe import install_moe_replay 

27from hyper_parallel.tools.dryrun.patches.registry import register_model_patch 

28from hyper_parallel.distributed.expert_parallel.collectives import ( 

29 _EPAllToAllPadded, 

30 ep_all_to_all, 

31) 

32from hyper_parallel.models import HyperAutoModelForCausalLM 

33from hyper_parallel.models.deepseek_v41.adapter.validation.cropped_model import build_deepseek_v41_validation_config 

34 

35 

36def _balanced_sparse_lookup( 

37 hash_ids: torch.Tensor, 

38 embedding: torch.nn.Embedding, 

39 *, 

40 ep_group: Any, 

41 ep_rank: int, 

42 ep_size: int, 

43 padded_num_embeddings: int, 

44) -> torch.Tensor: 

45 """Replay Engram routing with balanced, value-free EP traffic.""" 

46 num_local_rows = padded_num_embeddings // ep_size 

47 row_start = ep_rank * num_local_rows 

48 flat_ids = hash_ids.reshape(-1) 

49 owner = torch.div(flat_ids, num_local_rows, rounding_mode="floor") 

50 base, remainder = divmod(int(flat_ids.numel()), ep_size) 

51 counts = [base + int(index < remainder) for index in range(ep_size)] 

52 sort_indices = torch.argsort(owner.float(), stable=True) 

53 sorted_ids = flat_ids.index_select(0, sort_indices) 

54 received_ids = ep_all_to_all(sorted_ids, counts, counts, ep_group) 

55 values = embedding(received_ids - row_start) 

56 returned = ep_all_to_all(values, counts, counts, ep_group) 

57 restored = torch.zeros_like(returned) 

58 restored.scatter_add_( 

59 0, 

60 sort_indices.unsqueeze(1).expand(-1, returned.shape[1]), 

61 returned, 

62 ) 

63 return restored.view(*hash_ids.shape, embedding.embedding_dim) 

64 

65 

66def _fake_padded_all_to_all( 

67 ctx: Any, 

68 x: torch.Tensor, 

69 send_counts: list[int], 

70 recv_counts: list[int], 

71 group: Any, 

72) -> torch.Tensor: 

73 """Replay padded all-to-all without reading a value from fake MAX reduction.""" 

74 ctx.send_counts = send_counts 

75 ctx.recv_counts = recv_counts 

76 ctx.group = group 

77 ctx.pad_to = pad_to = max([*send_counts, *recv_counts, 1]) 

78 recv = _EPAllToAllPadded._pad_and_exchange( 

79 x, send_counts, pad_to, group) 

80 return _EPAllToAllPadded._unpad(recv, recv_counts, pad_to) 

81 

82 

83def install_deepseek_v41_replay() -> None: 

84 """Install DeepSeek V4.1 fake-value boundaries for the rest of the process. 

85 

86 Model-specific replay is requested by the model integration code below. 

87 Nothing is discovered from the module tree -- ``EngramModule`` also appears 

88 in other models whose replay needs differ -- and patches are never 

89 restored, because dry-run owns the process it runs in. 

90 """ 

91 EngramModule._sparse_lookup = staticmethod(_balanced_sparse_lookup) 

92 _EPAllToAllPadded.forward = staticmethod(_fake_padded_all_to_all) 

93 

94 

95def _synthetic_document_boundaries(sequence: Any) -> tuple[int, ...]: 

96 """Keep document count while assigning equal spans to value-free inputs.""" 

97 document_count = max(int(sequence.cu_seq_lens.numel()) - 1, 1) 

98 span, remainder = divmod(sequence.global_sequence_length, document_count) 

99 boundaries = [0] 

100 for index in range(1, document_count + 1): 

101 boundaries.append(boundaries[-1] + span + (index <= remainder)) 

102 return tuple(boundaries) 

103 

104 

105def _install_csa2_patches() -> None: 

106 """Make CSA2 host-side validations shape-only under FakeTensor. 

107 

108 Model-specific environment patch, registered from this example module so 

109 the generic dry-run compatibility layer never imports DeepSeek code. 

110 """ 

111 from hyper_parallel.components.modules.attention.compressed_sparse_attention2 import ( # pylint: disable=C0415 

112 SharedCompressedPackedSequence, 

113 ) 

114 

115 sequence_type = SharedCompressedPackedSequence 

116 if getattr(sequence_type, "_dryrun_compatibility_installed", False): 

117 return 

118 

119 original_document_boundaries = sequence_type.document_boundaries 

120 original_local_segment_starts = sequence_type.local_segment_starts 

121 

122 def document_boundaries(sequence: Any) -> tuple[int, ...]: 

123 """Return synthetic document boundaries for value-free sequences. 

124 

125 Args: 

126 sequence: Packed sequence whose document layout is requested. 

127 """ 

128 if not hasattr(sequence.cu_seq_lens, "fake_mode"): 

129 return original_document_boundaries(sequence) 

130 if "boundaries" not in sequence._snapshot: 

131 sequence._snapshot["boundaries"] = _synthetic_document_boundaries(sequence) 

132 return sequence._snapshot["boundaries"] 

133 

134 def local_segment_starts(sequence: Any, device: torch.device) -> torch.Tensor: 

135 """Return device-local segment starts that preserve the sequence shape. 

136 

137 Args: 

138 sequence: Packed sequence whose local segments are requested. 

139 device: Device the returned starts must live on. 

140 """ 

141 if not hasattr(sequence.cu_seq_lens, "fake_mode"): 

142 return original_local_segment_starts(sequence, device) 

143 cached = sequence._prepared_starts.get(torch.device(device)) 

144 if cached is not None: 

145 return cached 

146 boundaries = torch.tensor( 

147 document_boundaries(sequence), 

148 dtype=torch.long, 

149 device=device, 

150 ) 

151 query_positions = sequence.local_positions(device).squeeze(0) 

152 segment_ids = torch.bucketize(query_positions, boundaries[1:], right=True) 

153 result = boundaries[:-1].index_select(0, segment_ids).unsqueeze(0) 

154 sequence._prepared_starts[torch.device(device)] = result 

155 return result 

156 

157 sequence_type.document_boundaries = document_boundaries 

158 sequence_type.local_segment_starts = local_segment_starts 

159 sequence_type._dryrun_compatibility_installed = True 

160 

161 

162register_model_patch("deepseek_v41.engram", install_deepseek_v41_replay) 

163register_model_patch("deepseek_v41.csa2", _install_csa2_patches) 

164 

165 

166def _bind_chunk_loss(model: Any, chunks: int) -> None: 

167 """Compute a checkpointed output-head loss without full-sequence logits.""" 

168 if chunks < 1: 

169 raise ValueError("loss_chunks must be positive") 

170 

171 def _loss_chunk(hidden: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: 

172 """Compute one output-head cross-entropy chunk.""" 

173 logits = model.lm_head(hidden).float() 

174 return functional.cross_entropy( 

175 logits.reshape(-1, logits.size(-1)), targets.reshape(-1), 

176 ignore_index=-100, reduction="sum", 

177 ) 

178 

179 def _forward(current_model: Any, *, labels: torch.Tensor, **inputs: Any) -> CausalLMOutputWithPast: 

180 """Run the text model and checkpoint each output-head loss chunk.""" 

181 hidden = current_model.model(**inputs).last_hidden_state 

182 targets = functional.pad(labels[..., 1:], (0, 1), value=-100) 

183 if hidden.size(1) % chunks: 

184 raise ValueError("CP-local sequence length must be divisible by loss_chunks") 

185 loss = torch.zeros((), dtype=torch.float32, device=hidden.device) 

186 for hidden_chunk, target_chunk in zip(hidden.chunk(chunks, dim=1), targets.chunk(chunks, dim=1)): 

187 loss = loss + checkpoint(_loss_chunk, hidden_chunk, target_chunk, use_reentrant=False) 

188 return CausalLMOutputWithPast(loss=loss / targets.ne(-100).sum().clamp_min(1)) 

189 

190 model.forward = MethodType(_forward, model) 

191 

192 

193def build_text_model( 

194 config_path: str, 

195 engram_assets_path: str, 

196 *, 

197 num_hidden_layers: Optional[int] = None, 

198 text_parameter_divisor: int = 1, 

199 num_routed_experts: int = 384, 

200 loss_chunks: int = 8, 

201 **kwargs: Any, 

202) -> Any: 

203 """Build a released-size (or explicitly cropped) text model with chunk loss. 

204 

205 Args: 

206 config_path: Directory containing the released config.json. 

207 engram_assets_path: Engram validation asset generated for that config. 

208 num_hidden_layers: Optional decoder crop depth; ``None`` keeps all layers. 

209 text_parameter_divisor: 1 retains released text widths. 

210 num_routed_experts: 384 retains all released routed experts. 

211 loss_chunks: Number of CP-local loss chunks. 

212 **kwargs: Normal HyperAutoModel build settings supplied by Trainer. 

213 

214 Returns: 

215 Config-only model parallelized through the usual AutoModel path. 

216 """ 

217 config = build_deepseek_v41_validation_config( 

218 config_path, engram_assets_path, 

219 num_hidden_layers=num_hidden_layers, 

220 text_parameter_divisor=text_parameter_divisor, 

221 num_routed_experts=num_routed_experts, 

222 exercise_post_training_indexer=False, 

223 ) 

224 config.v41_model_mode = "full" 

225 model = HyperAutoModelForCausalLM.from_config(config, **kwargs) 

226 _bind_chunk_loss(model, loss_chunks) 

227 # Model-owned instance replay: class-level patches (Engram, CSA2) are 

228 # registered via register_model_patch at import time; MoE routing binds to 

229 # the constructed model and mesh here. 

230 setup = kwargs.get("distributed_setup") 

231 if setup is not None: 

232 install_moe_replay(model, setup.mesh_context, "balanced") 

233 return model