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

44 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 Flatten operator. 

17""" 

18from typing import Tuple 

19 

20from hyper_parallel.core.shard.ops.parallel_reshape import ReshapeDistributedOp 

21 

22 

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

24# pylint: disable-next=redefined-builtin 

25def _normalize_flatten_args(input, start_dim=0, end_dim=-1): 

26 return (input, start_dim, end_dim), {} 

27 

28 

29class FlattenDistributedOp(ReshapeDistributedOp): 

30 """Distributed implementation for torch.flatten.""" 

31 

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

33 """ 

34 Preprocess arguments for Flatten operator. 

35 

36 Args: 

37 args (tuple): Input tensor followed by optional start_dim and end_dim. 

38 kwargs (dict): Optional keyword arguments. 

39 

40 Returns: 

41 tuple: (local_args, local_kwargs, cache_values) 

42 """ 

43 args, _ = _normalize_flatten_args(*args, **kwargs) 

44 input_tensor, start_dim, end_dim = args[0], args[1], args[2] 

45 local_args = (input_tensor.to_local(), start_dim, end_dim) 

46 local_kwargs = {} 

47 cache_values = [input_tensor.layout, start_dim, end_dim, tuple(input_tensor.shape)] 

48 return local_args, local_kwargs, cache_values 

49 

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

51 """ 

52 Infer output layout for Flatten operator. 

53 

54 Rules: 

55 1. Partial input is allowed and preserved by reshape layout inference. 

56 2. input_shape must be provided and match the input rank. 

57 3. start_dim and end_dim must be integers within the valid input rank. 

58 4. If start_dim >= end_dim after normalization, the output layout is the 

59 input layout. 

60 5. Otherwise, dimensions from start_dim through end_dim are merged using 

61 reshape-compatible sharding rules. 

62 

63 Args: 

64 cache_values (list): [input_layout, start_dim, end_dim, input_shape]. 

65 

66 Returns: 

67 tuple: ((output_layout,), None) 

68 

69 Raises: 

70 ValueError: If cache_values are invalid, dimensions are out of range, 

71 or the flatten would change sharded slices incompatibly. 

72 """ 

73 input_layout, start_dim, end_dim, input_shape = ( 

74 cache_values[0], cache_values[1], cache_values[2], cache_values[3] 

75 ) 

76 if input_layout is None: 

77 raise ValueError( 

78 f"For {self.op_name}, flatten requires a valid input tensor layout." 

79 ) 

80 if not isinstance(input_shape, (list, tuple)): 

81 raise ValueError( 

82 f"For {self.op_name}, input_shape should be list or tuple, " 

83 f"but got {type(input_shape)}." 

84 ) 

85 if len(input_shape) != len(input_layout.tensor_map): 

86 raise ValueError( 

87 f"For {self.op_name}, input shape rank should match layout rank, " 

88 f"but got {len(input_shape)} and {len(input_layout.tensor_map)}." 

89 ) 

90 if not isinstance(start_dim, int) or not isinstance(end_dim, int): 

91 raise ValueError( 

92 f"For {self.op_name}, start_dim and end_dim should be int, " 

93 f"but got {type(start_dim)} and {type(end_dim)}." 

94 ) 

95 

96 ndim = len(input_shape) 

97 

98 if ndim == 0: 

99 out_layout = input_layout.__class__.from_device_mesh(input_layout.mesh) 

100 out_layout.set_placements(input_layout.placements) 

101 out_layout.placement_to_tensor_map(1) 

102 return ((out_layout,), None) 

103 

104 if start_dim < 0: 

105 start_dim += ndim 

106 if end_dim < 0: 

107 end_dim += ndim 

108 

109 start_dim_invalid = start_dim < 0 or start_dim >= ndim 

110 end_dim_invalid = end_dim < 0 or end_dim >= ndim 

111 if start_dim_invalid or end_dim_invalid: 

112 raise ValueError( 

113 f"For {self.op_name}, dimension out of range " 

114 f"(start_dim={start_dim}, end_dim={end_dim}, ndim={ndim})." 

115 ) 

116 

117 if start_dim >= end_dim: 

118 return ((input_layout,), None) 

119 

120 flattened_size = 1 

121 for i in range(start_dim, end_dim + 1): 

122 flattened_size *= input_shape[i] 

123 dst_shape = list(input_shape[:start_dim]) + [flattened_size] + list(input_shape[end_dim + 1:]) 

124 

125 out_layout, _ = self._infer_reshape_layout(input_layout, dst_shape, input_shape) 

126 return ((out_layout,), None)