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

62 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 

16""" 

17Distributed implementation for RepeatInterleave operator. 

18""" 

19import copy 

20from typing import Tuple 

21 

22from hyper_parallel.core.dtensor.layout import Layout 

23from .parallel_ops import DistributedOp 

24 

25 

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

27# pylint: disable-next=redefined-builtin 

28def _normalize_repeat_interleave_args(input, repeats, dim=None, *, output_size=None): 

29 """Normalize positional and keyword arguments into a canonical form. 

30 

31 Args: 

32 input: Input tensor. 

33 repeats: Number of repetitions (int or Tensor). 

34 dim: Dimension along which to repeat values. None means flatten first. 

35 output_size: Total output size (keyword-only in torch). 

36 

37 Returns: 

38 tuple: (positional_args_tuple, kwargs_dict) 

39 """ 

40 kwargs = {} 

41 if output_size is not None: 

42 kwargs['output_size'] = output_size 

43 return (input, repeats, dim), kwargs 

44 

45 

46class RepeatInterleaveDistributedOp(DistributedOp): 

47 """Distributed implementation for torch.repeat_interleave. 

48 

49 Sharding constraints: 

50 - When dim is specified: the repeat dimension must be replicated. 

51 - When dim is None (flatten mode): only the first dimension may be sharded. 

52 

53 Output layout: 

54 - When dim is specified: same as input layout. 

55 - When dim is None: 1-D layout preserving sharding on dim 0. 

56 """ 

57 

58 @staticmethod 

59 def _validate_input_layouts(input_layout, dim, op_name: str) -> None: 

60 """Validate sharding constraints for repeat_interleave. 

61 

62 Args: 

63 input_layout: Layout of the input tensor. 

64 dim: The repeat dimension, or None for flatten mode. 

65 op_name: Operator name used in error messages. 

66 

67 Raises: 

68 ValueError: If dim is out of range or the repeat dimension is sharded. 

69 """ 

70 in_tensor_map = input_layout.alias_tensor_map 

71 ndim = len(in_tensor_map) 

72 

73 if dim is not None: 

74 actual_dim = dim if dim >= 0 else ndim + dim 

75 if not 0 <= actual_dim < ndim: 

76 raise ValueError( 

77 f"For {op_name}, dimension should be in [0, {ndim}), but got {dim}." 

78 ) 

79 mapping = in_tensor_map[actual_dim] 

80 if isinstance(mapping, (list, tuple)): 

81 is_sharded = any(axis != "None" for axis in mapping) 

82 else: 

83 is_sharded = mapping != "None" 

84 if is_sharded: 

85 raise ValueError( 

86 f"For {op_name}, the repeat dimension should be replicated, " 

87 f"but got dim={dim} mapped to {mapping}." 

88 ) 

89 

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

91 """Preprocess arguments for RepeatInterleave operator. 

92 

93 Extracts local tensors from DTensor inputs and builds cache_values 

94 containing only the information needed for layout inference. 

95 

96 Args: 

97 args: Positional arguments (input, repeats, dim). 

98 kwargs: Keyword arguments (output_size). 

99 

100 Returns: 

101 tuple: (local_args, local_kwargs, cache_values) 

102 """ 

103 args, kwargs = _normalize_repeat_interleave_args(*args, **kwargs) 

104 input_tensor = args[0] 

105 repeats = args[1] 

106 dim = args[2] 

107 output_size = kwargs.get('output_size', None) 

108 

109 local_input = input_tensor.to_local() 

110 

111 # repeats can be int or Tensor; handle DTensor defensively 

112 if hasattr(repeats, 'to_local'): 

113 local_repeats = repeats.to_local() 

114 else: 

115 local_repeats = repeats 

116 

117 local_args = (local_input, local_repeats, dim) 

118 local_kwargs = {} 

119 if output_size is not None: 

120 local_kwargs['output_size'] = output_size 

121 

122 cache_values = [input_tensor.layout, dim] 

123 return local_args, local_kwargs, cache_values 

124 

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

126 """Infer output layout for RepeatInterleave operator. 

127 

128 Rules: 

129 1. Input must not have Partial status. 

130 2. When dim is specified: the repeat dimension must be replicated. 

131 Output layout is a deep copy of the input layout. 

132 3. When dim is None (flatten mode): only dim 0 may be sharded. 

133 Output is a 1-D layout preserving the mesh axis on dim 0. 

134 

135 Args: 

136 cache_values: [input_layout, dim] where dim is the repeat dimension 

137 or None for flatten mode. 

138 

139 Returns: 

140 tuple: ((output_layout,), None) 

141 

142 Raises: 

143 ValueError: If input has Partial status, dim is out of range, 

144 the repeat dimension is sharded, or flatten is attempted on 

145 a tensor sharded on a non-first dimension. 

146 """ 

147 input_layout = cache_values[0] 

148 dim = cache_values[1] 

149 

150 self._check_partial_inputs([input_layout]) 

151 self._validate_input_layouts(input_layout, dim, self.op_name) 

152 

153 in_tensor_map = input_layout.alias_tensor_map 

154 

155 if dim is None: 

156 # Flatten mode: output is 1-D. 

157 sharded_dims = [] 

158 for i, shard in enumerate(in_tensor_map): 

159 if isinstance(shard, (list, tuple)): 

160 is_sharded = any(axis != "None" for axis in shard) 

161 else: 

162 is_sharded = shard != "None" 

163 if is_sharded: 

164 sharded_dims.append(i) 

165 if not sharded_dims: 

166 output_tensor_map = ("None",) 

167 elif sharded_dims == [0]: 

168 output_tensor_map = (in_tensor_map[0],) 

169 else: 

170 raise ValueError( 

171 f"For {self.op_name}, sharded dims in flatten mode should be [] or [0], " 

172 f"but got {sharded_dims}." 

173 ) 

174 

175 output_layout = Layout( 

176 mesh_shape=input_layout.mesh_shape, 

177 alias_name=input_layout.alias_name, 

178 rank_list=input_layout.rank_list 

179 ) 

180 return (output_layout(*output_tensor_map),), None 

181 

182 # dim specified: output layout = deep copy of input layout 

183 return (copy.deepcopy(input_layout),), None