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

63 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 Transpose operator. 

17""" 

18 

19from typing import Tuple 

20 

21from hyper_parallel.core.dtensor.layout import Layout 

22from .parallel_ops import DistributedOp 

23 

24 

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

26# pylint: disable-next=redefined-builtin 

27def _normalize_transpose_args(input, dim0, dim1): 

28 return (input, dim0, dim1), {} 

29 

30 

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

32# pylint: disable-next=redefined-builtin 

33def _normalize_permute_args(input, *args, dims=None): 

34 """Accept both torch.permute(input, dims) and Tensor.permute(*dims).""" 

35 if dims is not None: 

36 if args: 

37 raise TypeError("permute got dims from both args and kwargs.") 

38 else: 

39 dims = args[0] if len(args) == 1 else args 

40 return (input, dims), {} 

41 

42 

43class TransposeDistributedOp(DistributedOp): 

44 """Distributed implementation for Transpose operator.""" 

45 

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

47 """ 

48 Preprocess arguments for Transpose operator. 

49 

50 Args: 

51 args (tuple): Input arguments, first element is the input tensor. 

52 kwargs (dict): Keyword arguments (input, dims, dim0, dim1). 

53 

54 Returns: 

55 tuple: (local_args, local_kwargs, cache_values) 

56 """ 

57 if self.op_name in ("Transpose", "permute", "TransposeView"): 

58 args, _ = _normalize_permute_args(*args, **kwargs) 

59 input_tensor = args[0] 

60 axis = args[1] 

61 local_args = (input_tensor.to_local(), axis) 

62 local_kwargs = {} 

63 cache_values = [input_tensor.layout, axis] 

64 elif self.op_name in ("transpose", "TransposeExtView"): 

65 args, _ = _normalize_transpose_args(*args, **kwargs) 

66 input_tensor = args[0] 

67 dim0, dim1 = args[1], args[2] 

68 local_args = (input_tensor.to_local(), dim0, dim1) 

69 local_kwargs = {} 

70 cache_values = [input_tensor.layout, dim0, dim1] 

71 else: 

72 raise ValueError( 

73 f"For TransposeDistributedOp, unsupported op_name: {self.op_name}. " 

74 f"Expected 'Transpose', 'transpose', 'permute', " 

75 f"'TransposeView', or 'TransposeExtView'." 

76 ) 

77 

78 return local_args, local_kwargs, cache_values 

79 

80 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]: 

81 """ 

82 Infer output layout for Transpose operator. 

83 

84 Based on the op_name initialized in the base class, this method switches behavior: 

85 1. op_name == 'Transpose', 'permute' or 'TransposeView': axis-based permutation. 

86 - cache_values: [input_layout, axis] where axis is a tuple of indices. 

87 - Rules: Output tensor_map is permuted according to axis. 

88 2. op_name == 'transpose' or 'TransposeExtView': dim-based swap. 

89 - cache_values: [input_layout, dim0, dim1] where dim0 and dim1 are integers. 

90 - Rules: Output tensor_map has the two dimensions swapped. 

91 

92 Rules: 

93 1. Input must not have Partial status. 

94 2. For axis-based: axis must be a valid permutation of [0, ndim-1]. 

95 3. For dim-based: dim0 and dim1 must be integers within [-ndim, ndim-1]. 

96 4. Output layout inherits mesh info from input, with tensor_map permuted accordingly. 

97 

98 Args: 

99 cache_values (list): [input_layout, ...] where the remaining elements depend on op_name. 

100 

101 Returns: 

102 tuple: ((output_layout,), None) 

103 

104 Raises: 

105 ValueError: If any rule above is violated. 

106 """ 

107 layout = cache_values[0] 

108 if not self._allow_partial_inputs: 

109 self._check_partial_inputs([layout]) 

110 

111 in_tensor_map = layout.alias_tensor_map 

112 ndim = len(in_tensor_map) 

113 

114 if self.op_name in ("Transpose", "permute", "TransposeView"): 

115 axis = cache_values[1] 

116 

117 if not isinstance(axis, (list, tuple)): 

118 raise ValueError( 

119 f"For {self.op_name}, axis should be a list or tuple, " 

120 f"but got {type(axis)}." 

121 ) 

122 

123 if len(in_tensor_map) != len(axis): 

124 raise ValueError( 

125 f"For {self.op_name}, input tensor shape and permutation " 

126 f"must have the same size. " 

127 f"Got {len(in_tensor_map)} and {len(axis)}." 

128 ) 

129 

130 # check if axis is a permutation 

131 seen = set() 

132 for v in axis: 

133 if not isinstance(v, int): 

134 raise ValueError( 

135 f"For {self.op_name}, axis elements must be integers, " 

136 f"but got {type(v)}." 

137 ) 

138 if v < 0 or v >= ndim or v in seen: 

139 raise ValueError( 

140 f"For {self.op_name}, invalid permutation {axis} for rank {ndim}." 

141 ) 

142 seen.add(v) 

143 

144 out_tensor_map = tuple(in_tensor_map[i] for i in axis) 

145 

146 else: 

147 dim0, dim1 = cache_values[1], cache_values[2] 

148 

149 if not isinstance(dim0, int) or not isinstance(dim1, int): 

150 raise ValueError( 

151 f"For {self.op_name}, dimensions must be integers, " 

152 f"but got {type(dim0)} and {type(dim1)}." 

153 ) 

154 

155 if dim0 < 0: 

156 dim0 += ndim 

157 if dim1 < 0: 

158 dim1 += ndim 

159 

160 if not (0 <= dim0 < ndim and 0 <= dim1 < ndim): 

161 raise ValueError( 

162 f"For {self.op_name}, transpose dimensions out of bounds: " 

163 f"({dim0}, {dim1}) for rank {ndim}." 

164 ) 

165 

166 out_tensor_map_list = list(in_tensor_map) 

167 out_tensor_map_list[dim0], out_tensor_map_list[dim1] = ( 

168 out_tensor_map_list[dim1], out_tensor_map_list[dim0] 

169 ) 

170 out_tensor_map = tuple(out_tensor_map_list) 

171 

172 output_layout = Layout( 

173 mesh_shape=layout.mesh_shape, 

174 alias_name=layout.alias_name, 

175 rank_list=layout.rank_list 

176 ) 

177 

178 return ((output_layout(*out_tensor_map),), None)