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

39 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 Nonzero 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_nonzero_args(input, as_tuple=False): 

28 return (input,), {'as_tuple': as_tuple} 

29 

30 

31class NonzeroDistributedOp(DistributedOp): 

32 """Distributed implementation for torch.nonzero.""" 

33 

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

35 """ 

36 Preprocess arguments for Nonzero operator. 

37 

38 Args: 

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

40 kwargs (dict): Keyword arguments (as_tuple). 

41 

42 Returns: 

43 tuple: (local_args, local_kwargs, cache_values) 

44 """ 

45 args, kwargs = _normalize_nonzero_args(*args, **kwargs) 

46 input_tensor = args[0] 

47 as_tuple = kwargs['as_tuple'] 

48 

49 local_args = (input_tensor.to_local(),) 

50 local_kwargs = {'as_tuple': as_tuple} 

51 

52 cache_values = [input_tensor.layout, as_tuple] 

53 return local_args, local_kwargs, cache_values 

54 

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

56 """ 

57 Infer output layouts for Nonzero operator. 

58 

59 Rules: 

60 1. Input must not have Partial status. 

61 2. Input must be fully replicated (all dimensions mapped to "None"). 

62 nonzero produces data-dependent output shapes, which would differ 

63 across sharded ranks. 

64 3. If as_tuple=True: returns a tuple of 1D replicated layouts, one per 

65 input dimension. 

66 4. If as_tuple=False: returns a single 2D replicated layout. 

67 

68 Args: 

69 cache_values (list): [input_layout, as_tuple] 

70 

71 Returns: 

72 tuple: ((output_layout(s),), None) 

73 

74 Raises: 

75 ValueError: If input has Partial status or is sharded. 

76 """ 

77 input_layout = cache_values[0] 

78 as_tuple = cache_values[1] 

79 

80 if input_layout is None: 

81 raise ValueError( 

82 f"For {self.op_name}, input_layout should be a valid Layout, but got None." 

83 ) 

84 

85 # Rule 1: Input must not have Partial status 

86 if not self._allow_partial_inputs: 

87 self._check_partial_inputs([input_layout]) 

88 

89 if not isinstance(as_tuple, bool): 

90 raise ValueError( 

91 f"For {self.op_name}, as_tuple should be bool, but got {type(as_tuple)}." 

92 ) 

93 

94 alias_map = input_layout.alias_tensor_map 

95 input_ndim = len(alias_map) 

96 

97 # Rule 2: Input must be fully replicated due to data-dependent dynamic shapes 

98 for dim, dim_sharding in enumerate(alias_map): 

99 if dim_sharding != "None": 

100 raise ValueError( 

101 f"For {self.op_name}, input tensor should be fully replicated, " 

102 f"but got dim {dim} mapped to {dim_sharding}. " 

103 f"nonzero produces dynamic shapes that depend on data values, " 

104 f"which causes shape mismatches across ranks if the tensor is sharded." 

105 ) 

106 

107 mesh_shape = input_layout.mesh_shape 

108 alias_name = input_layout.alias_name 

109 rank_list = input_layout.rank_list 

110 

111 def _create_replicated_layout(ndim): 

112 """Helper to create a fully replicated layout for a given dimension.""" 

113 layout = Layout( 

114 mesh_shape=mesh_shape, 

115 alias_name=alias_name, 

116 rank_list=rank_list 

117 ) 

118 alias_map = tuple("None" for _ in range(ndim)) 

119 return layout(*alias_map) 

120 

121 # Rule 3 & 4: Construct the return layout based on as_tuple flag 

122 if as_tuple: 

123 out_layout = _create_replicated_layout(1) 

124 return (tuple(out_layout for _ in range(input_ndim)), None) 

125 

126 return ((_create_replicated_layout(2),), None)