Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_embedding.py: 90%

96 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"""Distributed implementation for the embedding operator.""" 

16 

17from typing import Callable, Optional, Tuple 

18 

19from hyper_parallel.core.dtensor.layout import Layout 

20from .parallel_ops import DistributedOp 

21 

22 

23# Preserve Torch keyword names for calls forwarded by __torch_function__. 

24# pylint: disable-next=redefined-builtin 

25def _normalize_embedding_args(input, weight, padding_idx=None, max_norm=None, 

26 norm_type=2.0, scale_grad_by_freq=False, sparse=False): 

27 return ( 

28 input, 

29 weight, 

30 padding_idx, 

31 max_norm, 

32 norm_type, 

33 scale_grad_by_freq, 

34 sparse, 

35 ), {} 

36 

37 

38class EmbeddingDistributedOp(DistributedOp): 

39 """ 

40 Distributed implementation for embedding operators. 

41 Supports Column Parallelism (CP) and Row Parallelism (RP). 

42 """ 

43 

44 def preprocess(self, args: tuple, kwargs: dict) -> tuple: 

45 """ 

46 Preprocess arguments for Embedding operator. 

47 

48 Args: 

49 args (tuple): Input arguments containing input and weight tensors. 

50 kwargs (dict): Keyword arguments for embedding options. 

51 

52 Returns: 

53 tuple: (local_args, local_kwargs, cache_values) where cache_values is 

54 [input_layout, weight_layout]. 

55 """ 

56 args, _ = _normalize_embedding_args(*args, **kwargs) 

57 input_tensor, weight_tensor = args[0], args[1] 

58 local_args = (input_tensor.to_local(), weight_tensor.to_local()) + args[2:] 

59 local_kwargs = {} 

60 cache_values = [input_tensor.layout, weight_tensor.layout] 

61 return local_args, local_kwargs, cache_values 

62 

63 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]: # pylint: disable=W0221 

64 """ 

65 Infer output layout for Embedding operator. 

66 

67 Rules: 

68 1. Input and weight must not have Partial status. 

69 2. Input and weight must share the same mesh_shape. 

70 3. Weight must be 2D [vocab_size, embedding_dim]. 

71 4. Output shape is [*input_shape, embedding_dim], preserving input sharding 

72 and inheriting weight embedding-dimension sharding. 

73 5. If weight vocab dimension is sharded, output carries Partial('sum') on 

74 that vocab sharding axis. 

75 

76 Args: 

77 cache_values (list): [input_layout, weight_layout]. 

78 

79 Returns: 

80 tuple: ((output_layout,), None) 

81 

82 Raises: 

83 ValueError: If layouts are missing, partial, incompatible, or weight is not 2D. 

84 """ 

85 if len(cache_values) != 2: 

86 raise ValueError( 

87 f"For {self.op_name}, cache_values length should be 2, but got {len(cache_values)}" 

88 ) 

89 

90 input_layout = cache_values[0] 

91 weight_layout = cache_values[1] 

92 if not input_layout or not weight_layout: 

93 raise ValueError( 

94 f"For {self.op_name}, requires both input and weight layouts." 

95 ) 

96 

97 self._check_partial_inputs([input_layout, weight_layout]) 

98 

99 if input_layout.mesh_shape != weight_layout.mesh_shape: 

100 raise ValueError( 

101 f"For {self.op_name}, input and weight must have the same mesh_shape, " 

102 f"but got input: {input_layout.mesh_shape} and weight: {weight_layout.mesh_shape}" 

103 ) 

104 

105 weight_tensor_map = weight_layout.tensor_map 

106 if len(weight_tensor_map) != 2: 

107 raise ValueError( 

108 f"For {self.op_name}, weight should be 2D [vocab_size, embedding_dim], " 

109 f"but got {len(weight_tensor_map)}D" 

110 ) 

111 

112 # weight_tensor_map: [vocab_size_dim, embed_dim_dim] 

113 w_shard_embed_axis = weight_tensor_map[1] 

114 weight_alias_map = weight_layout.alias_tensor_map 

115 w_shard_vocab_alias = weight_alias_map[0] 

116 

117 # Output shape is [*input_shape, embed_dim] 

118 output_tensor_map = list(input_layout.tensor_map) 

119 output_tensor_map.append(w_shard_embed_axis) 

120 

121 output_layout = Layout( 

122 mesh_shape=input_layout.mesh_shape, 

123 alias_name=input_layout.alias_name, 

124 rank_list=input_layout.rank_list 

125 ) 

126 output_layout.set_tensor_map(tuple(output_tensor_map)) 

127 

128 # If vocab is sharded (Row Parallelism), output is in Partial Sum state 

129 if w_shard_vocab_alias != "None": 

130 # pylint: disable=protected-access 

131 output_layout._partial = list(input_layout.partial) 

132 output_layout.set_partial_by_dev_axis(w_shard_vocab_alias, 'sum') 

133 # pylint: disable=protected-access 

134 output_layout._alias_tensor_map = output_layout._build_readable_tensor_map() 

135 # pylint: disable=protected-access 

136 output_layout.tensor_map_to_placement() 

137 output_layout.update_compact_str() 

138 

139 return ((output_layout,), None) 

140 

141 def _parse_params(self, args, kwargs): 

142 """ 

143 Extracts padding_idx, max_norm, and scale_grad from args or kwargs. 

144 F.embedding signature: (input, weight, padding_idx, max_norm, norm_type, scale_grad_by_freq...) 

145 """ 

146 padding_idx = args[2] if len(args) > 2 else kwargs.get('padding_idx', None) 

147 max_norm = args[3] if len(args) > 3 else kwargs.get('max_norm', None) 

148 scale_grad = args[5] if len(args) > 5 else kwargs.get('scale_grad_by_freq', False) 

149 return padding_idx, max_norm, scale_grad 

150 

151 def _handle_rp_input(self, input_tensor, weight_tensor, weight_layout, w_shard_vocab_axis, 

152 new_args, kwargs, is_args_pad, padding_idx): 

153 """ 

154 Processes Row Parallelism input: shifts indices, handles padding, and generates masks. 

155 """ 

156 mesh = weight_layout.mesh 

157 mesh_dim_idx = len(mesh.mesh_shape) - 1 - w_shard_vocab_axis 

158 vocab_coord = mesh.get_local_rank(mesh_dim_idx) 

159 

160 vocab_size_per_partition = weight_tensor.shape[0] 

161 vocab_start_index = int(vocab_coord * vocab_size_per_partition) 

162 vocab_end_index = int(vocab_start_index + vocab_size_per_partition) 

163 

164 # Map global padding_idx to local rank range 

165 if padding_idx is not None: 

166 if vocab_start_index <= padding_idx < vocab_end_index: 

167 mapped_padding_idx = int(padding_idx - vocab_start_index) 

168 if is_args_pad: 

169 new_args[2] = mapped_padding_idx 

170 else: 

171 kwargs['padding_idx'] = mapped_padding_idx 

172 else: 

173 if is_args_pad: 

174 new_args[2] = None 

175 else: 

176 kwargs.pop('padding_idx', None) 

177 

178 # Calculate out-of-bounds mask 

179 mask = (input_tensor >= vocab_start_index) & (input_tensor < vocab_end_index) 

180 

181 # Cross-platform cast to matching int dtype 

182 mask_int = mask.to(input_tensor.dtype) if hasattr(mask, "to") else mask.astype(input_tensor.dtype) 

183 

184 # Shift global indices to local range using native scalar broadcast 

185 local_input = input_tensor - vocab_start_index 

186 

187 # Zero out invalid indices mathematically instead of using .where() or clamp(). 

188 # This prevents NPU out-of-bounds memory access during the embedding lookup 

189 # while keeping the code perfectly backend-neutral. 

190 local_input = local_input * mask_int 

191 

192 return local_input, mask_int 

193 

194 def get_expand_impl(self, func: Optional[Callable], infer_result: tuple, # pylint: disable=W0221 

195 cache_values: list) -> Optional[Callable]: 

196 """ 

197 Returns the execution implementation wrapper. 

198 Helper functions are used to keep Cyclomatic Complexity (CCN) low. 

199 """ 

200 weight_layout = cache_values[1] 

201 w_shard_vocab_axis = weight_layout.tensor_map[0] 

202 weight_alias_map = weight_layout.alias_tensor_map 

203 w_shard_vocab_alias = weight_alias_map[0] 

204 w_shard_embed_alias = weight_alias_map[1] 

205 

206 # Use native implementation if no weight sharding is applied 

207 if w_shard_vocab_alias == "None" and w_shard_embed_alias == "None": 

208 return None 

209 

210 def distributed_embedding_impl(*args, **kwargs): 

211 input_tensor, weight_tensor = args[0], args[1] 

212 new_args, new_kwargs = list(args), kwargs.copy() 

213 

214 # 1. Parameter extraction and validation 

215 padding_idx, max_norm, scale_grad = self._parse_params(args, kwargs) 

216 

217 # Check for max_norm with specific error messages for CP and RP 

218 if max_norm is not None: 

219 if w_shard_embed_alias != "None": 

220 raise ValueError( 

221 f"For {self.op_name}, Column-Parallel Embedding does not support `max_norm` parameter." 

222 ) 

223 if w_shard_vocab_alias != "None": 

224 raise ValueError( 

225 f"For {self.op_name}, Row-Parallel Embedding does not support `max_norm` parameter." 

226 ) 

227 

228 # Check for scale_grad_by_freq with RP 

229 if scale_grad and w_shard_vocab_alias != "None": 

230 raise ValueError( 

231 f"For {self.op_name}, Row-Parallel Embedding does not support `scale_grad_by_freq=True`." 

232 ) 

233 

234 # 2. Row Parallel Processing 

235 input_mask_int = None 

236 if w_shard_vocab_alias != "None": 

237 is_args_pad = len(args) > 2 

238 mapped_input, input_mask_int = self._handle_rp_input( 

239 input_tensor, weight_tensor, weight_layout, w_shard_vocab_axis, 

240 new_args, new_kwargs, is_args_pad, padding_idx 

241 ) 

242 new_args[0] = mapped_input 

243 

244 # 3. Native Operator Execution 

245 output = func(*new_args, **new_kwargs) 

246 

247 # 4. Erase invalid partial embeddings (Row-Parallel only) 

248 if w_shard_vocab_alias != "None" and input_mask_int is not None: 

249 expanded_mask = input_mask_int[..., None].to(output.dtype) 

250 output = output * expanded_mask 

251 

252 return output 

253 

254 return distributed_embedding_impl