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

58 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""" 

16Distributed implementation for Repeat operator. 

17""" 

18 

19from typing import Tuple 

20 

21from hyper_parallel.core.dtensor.layout import Layout 

22from .parallel_ops import DistributedOp 

23 

24 

25def _normalize_repeat_args(x, *sizes, repeats=None): 

26 if repeats is not None: 

27 if sizes: 

28 raise TypeError("repeat got repeats from both args and kwargs.") 

29 sizes = (repeats,) 

30 return (x,) + sizes, {} 

31 

32 

33class RepeatDistributedOp(DistributedOp): 

34 """Distributed implementation for torch.Tensor.repeat.""" 

35 

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

37 """ 

38 Preprocess arguments for torch.Tensor.repeat. 

39 

40 Args: 

41 args (tuple): Input tensor followed by repeat sizes. 

42 kwargs (dict): Keyword arguments. 

43 

44 Returns: 

45 tuple: (local_args, local_kwargs, cache_values) 

46 """ 

47 args, _ = _normalize_repeat_args(*args, **kwargs) 

48 input_tensor = args[0] 

49 sizes = args[1:] 

50 

51 local_args = (input_tensor.to_local(),) + sizes 

52 local_kwargs = {} 

53 cache_values = [input_tensor.layout, sizes] 

54 return local_args, local_kwargs, cache_values 

55 

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

57 """ 

58 Infer output layout for torch.Tensor.repeat. 

59 

60 PyTorch semantics: 

61 - Repeats this tensor along the specified dimensions. 

62 - If the number of repeat dimensions is larger than the tensor dimensions, 

63 the tensor is implicitly unsqueezed at the front. 

64 - The number of repeat dimensions cannot be smaller than the tensor dimensions. 

65 - Dimensions being repeated (>1 or 0) MUST be unsharded. 

66 

67 Rules: 

68 1. Input must not have Partial status. 

69 2. Repeat sizes must be provided. 

70 3. New prepended dimensions are unsharded. 

71 4. Existing dimensions with repeat size 1 preserve the input sharding. 

72 5. Existing dimensions with repeat size other than 1 must not be sharded. 

73 

74 Args: 

75 cache_values (list): [input_layout, repeat_sizes]. 

76 

77 Returns: 

78 tuple: ((output_layout,), None) 

79 

80 Raises: 

81 ValueError: If input layout is missing, input has Partial status, repeat sizes 

82 are missing, or a sharded dimension is repeated. 

83 """ 

84 if not cache_values or cache_values[0] is None: 

85 raise ValueError( 

86 f"For {self.op_name}, repeat requires a valid input tensor layout." 

87 ) 

88 

89 input_layout = cache_values[0] 

90 self._check_partial_inputs([input_layout]) 

91 

92 in_tensor_map = input_layout.tensor_map 

93 in_alias_map = input_layout.alias_tensor_map 

94 input_ndim = len(in_tensor_map) 

95 

96 if len(cache_values) < 2 or not cache_values[1]: 

97 raise ValueError( 

98 f"For {self.op_name}, repeat requires repeat sizes in cache_values." 

99 ) 

100 

101 # Robustly handle sizes unpacking (e.g., if args are packed as a single tuple) 

102 repeat_sizes = cache_values[1] 

103 if len(repeat_sizes) == 1 and isinstance(repeat_sizes[0], (tuple, list)): 

104 flat_args = repeat_sizes[0] 

105 else: 

106 flat_args = repeat_sizes 

107 

108 # Normalize repeat sizes to tuple of ints 

109 repeats = [] 

110 for arg in flat_args: 

111 if not isinstance(arg, int): 

112 arg = int(arg) 

113 repeats.append(arg) 

114 repeats = tuple(repeats) 

115 output_ndim = len(repeats) 

116 

117 num_new_dims = output_ndim - input_ndim 

118 output_map = [] 

119 

120 # Rule 1: New prepended dimensions are always unsharded 

121 for _ in range(num_new_dims): 

122 output_map.append("None") 

123 

124 # Rule 2: Process existing dimensions 

125 for i in range(input_ndim): 

126 repeat_idx = num_new_dims + i 

127 repeat_times = repeats[repeat_idx] 

128 

129 if repeat_times == 1: 

130 # If the dimension is not repeated, keep the original sharding 

131 output_map.append(in_alias_map[i]) 

132 else: 

133 # If the dimension is repeated (or zeroed), it cannot be currently sharded 

134 mapping = in_alias_map[i] 

135 if mapping != "None": 

136 raise ValueError( 

137 f"For {self.op_name}, Cannot repeat dimension {i} which is sharded. " 

138 f"Please redistribute (unshard) the tensor along this dimension first." 

139 ) 

140 # Repeated dimension remains unsharded in output 

141 output_map.append("None") 

142 

143 # Construct output layout mapping 

144 mesh_shape = input_layout.mesh_shape 

145 alias_name = input_layout.alias_name 

146 rank_list = input_layout.rank_list 

147 

148 # Instantiate new layout 

149 output_layout = Layout( 

150 mesh_shape=mesh_shape, 

151 alias_name=alias_name, 

152 rank_list=rank_list 

153 ) 

154 output_layout = output_layout(*output_map) 

155 

156 return ((output_layout,), None)