Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / compile / passes / graph_metadata.py: 97%

76 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"""Shared FX storage, host-boundary and fake-value contracts for execution passes.""" 

16 

17from __future__ import annotations 

18 

19from collections import defaultdict 

20import operator 

21from typing import Any 

22 

23import torch 

24from torch import fx 

25from torch._ops import OpOverload, OpOverloadPacket 

26from torch._subclasses.fake_tensor import FakeTensor 

27from torch.fx.experimental.symbolic_shapes import has_free_unbacked_symbols 

28from torch.fx.passes.fake_tensor_prop import FakeTensorProp 

29from torch.multiprocessing.reductions import StorageWeakRef 

30from torch.utils._pytree import tree_leaves 

31 

32 

33def _native_overload(target): 

34 if isinstance(target, OpOverload): 

35 return target 

36 if isinstance(target, OpOverloadPacket) and target.overloads() == ["default"]: 

37 return target.default 

38 return None 

39 

40 

41def tensor_storages(node: fx.Node) -> set[StorageWeakRef]: 

42 """Return storage identities, including tensor leaves of structured values.""" 

43 return {StorageWeakRef(value.untyped_storage()) for value in tree_leaves(node.meta.get("val")) 

44 if isinstance(value, torch.Tensor)} 

45 

46 

47def written_nodes(node: fx.Node) -> list[fx.Node]: 

48 """Resolve writes, conservatively treating unknown host helpers as mutable. 

49 

50 Args: 

51 node: FX operation whose input writes are inspected. 

52 

53 Returns: 

54 Input nodes whose tensor storage may be modified by the operation. 

55 """ 

56 inputs = node.all_input_nodes 

57 overload = _native_overload(node.target) 

58 if overload is None: 

59 if node.op in ("call_function", "call_method", "call_module") and node.target is not operator.getitem: 

60 return list(inputs) 

61 return [] 

62 result = [] 

63 # OpOverload exposes argument alias/write metadata only through its native schema. 

64 for index, argument in enumerate(overload._schema.arguments): # pylint: disable=protected-access 

65 if (argument.alias_info and argument.alias_info.is_write) or ( 

66 overload.namespace == "c10d" and "Tensor" in str(argument.type) 

67 ): 

68 value = node.args[index] if index < len(node.args) else node.kwargs.get(argument.name) 

69 result.extend(leaf for leaf in tree_leaves(value) if isinstance(leaf, fx.Node)) 

70 return result 

71 

72 

73def mutated_input_indices(graph_module: fx.GraphModule) -> set[int]: 

74 """Find input mutations through views, structured values or host helpers.""" 

75 storage_inputs = defaultdict(set) 

76 for index, node in enumerate(graph_module.graph.find_nodes(op="placeholder")): 

77 for storage in tensor_storages(node): 

78 storage_inputs[storage].add(index) 

79 mutated = set() 

80 for node in graph_module.graph.nodes: 

81 for written in written_nodes(node): 

82 for storage in tensor_storages(written): 

83 mutated.update(storage_inputs[storage]) 

84 return mutated 

85 

86 

87def _is_routed_expert_node(node: fx.Node) -> bool: 

88 custom = node.meta.get("custom", {}) 

89 if custom.get("expert_parallel", False) or custom.get("routed_experts", False): 

90 return True 

91 fqns = [custom.get("module_fqn", "")] 

92 fqns.extend(fqn for fqn, _ in (node.meta.get("nn_module_stack") or {}).values()) 

93 return any(part in ("experts", "routed_experts") for fqn in fqns for part in fqn.split(".")) 

94 

95 

96def _requires_eager_callable(node, overload): 

97 opaque = overload is None and node.target is not operator.getitem 

98 # Stateful c10d returns Work objects and does not expose its writes in the schema. 

99 return ( 

100 (overload is not None and overload.namespace == "c10d") 

101 or any( 

102 isinstance(parent.target, OpOverload) and parent.target.namespace == "c10d" 

103 for parent in node.all_input_nodes 

104 ) 

105 or opaque 

106 ) 

107 

108 

109def is_host_node(node: fx.Node) -> bool: 

110 """Keep host work and dynamic routed-expert layouts outside device recording. 

111 

112 Args: 

113 node: FX operation being considered for device recording. 

114 

115 Returns: 

116 Whether the operation must execute eagerly outside a device graph. 

117 """ 

118 # The scalar-read ATen symbol marks a host synchronization boundary in traced graphs. 

119 overload = _native_overload(node.target) 

120 return ( 

121 node.op in ("call_module", "call_method") 

122 or _is_routed_expert_node(node) 

123 or _requires_eager_callable(node, overload) 

124 or overload == torch.ops.aten._local_scalar_dense.default # pylint: disable=protected-access 

125 or any( 

126 (isinstance(value, torch.Tensor) 

127 and (value.device.type == "cpu" or has_free_unbacked_symbols(value))) 

128 or (isinstance(value, (torch.SymInt, torch.SymFloat, torch.SymBool)) 

129 and has_free_unbacked_symbols(value)) 

130 for parent in (node, *node.all_input_nodes) for value in tree_leaves(parent.meta.get("val")) 

131 ) 

132 ) 

133 

134 

135def propagate_fake_values( 

136 graph_module: fx.GraphModule, 

137 example_inputs: tuple[Any, ...] | None = None, 

138 model: torch.nn.Module | None = None, 

139) -> fx.GraphModule: 

140 """Refresh metadata before lowering, using physically sharded model state. 

141 

142 Args: 

143 graph_module: FX graph whose tensor metadata is refreshed. 

144 example_inputs: Fallback values for placeholders without metadata. 

145 model: Live model providing the current physical parameter and buffer layouts. 

146 

147 Returns: 

148 The input graph with refreshed fake-value metadata when a fake mode is available. 

149 """ 

150 placeholders = list(graph_module.graph.find_nodes(op="placeholder")) 

151 values = [node.meta.get("val") for node in placeholders] 

152 if example_inputs is not None: 

153 values = [value if value is not None else example_inputs[index] for index, value in enumerate(values)] 

154 mode = next((value.fake_mode for value in values if isinstance(value, FakeTensor)), None) 

155 if mode is None: 

156 return graph_module 

157 if model is not None: 

158 state = dict(model.named_parameters(remove_duplicate=False)) 

159 state.update(model.named_buffers(remove_duplicate=False)) 

160 for index, fqn in enumerate(getattr(graph_module, "state_fqns", ())): 

161 values[index] = mode.from_tensor(state[fqn].detach(), static_shapes=True) 

162 # ProcessGroup arguments cannot compare equal in the FakeTensor dispatch cache. 

163 cache_enabled = mode.cache_enabled 

164 mode.cache_enabled = False 

165 try: 

166 FakeTensorProp(graph_module, mode).propagate_dont_convert_inputs(*values) 

167 finally: 

168 mode.cache_enabled = cache_enabled 

169 return graph_module