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

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

16Pass Pipeline - Pass Orchestrator 

17 

18Automatically builds Pass execution order based on parallel configuration. 

19 

20Execution Order: 

211. Basic optimization: DeadCodeElimination, CanonicalizeGraph 

222. Activation checkpointing: ActivationCheckpointPass (``ac_mode`` != off) 

23 runs on the plain joint graph BEFORE FSDPPass, so recomputed duplicates 

24 are ordinary forward ops when the FSDP collectives are inserted (their 

25 ``autograd_backward`` tag makes FSDPPass count them as backward 

26 consumers and re-gather parameters for them). Running AC after FSDP 

27 would make recompute read sharded placeholders. 

282b. CPU offload: CpuOffloadPass (``activation_swap`` != none) moves saved 

29 attention activations to host memory. It runs before FSDP so reload nodes 

30 become ordinary backward consumers for parameter re-gathers. Attention swap 

31 is incompatible with activation checkpointing (enforced in ``PassConfig``), 

32 so it never runs alongside recompute. 

333. Execution layer: 

34 - FSDPPass (FSDP) 

35 - FsdpBucketingPass (opt-in AG/RS fusion; supports FSDP with PP disabled). 

36 - PpPass (pipeline-parallel stage split) — runs AFTER FSDPPass: the FSDP 

37 collectives are value-level FX nodes that follow the data flow, so the 

38 stage slices inherit this stage's all_gather/reduce_scatter untouched 

39 while foreign stages' collectives are simply never copied. Splitting 

40 first would hand FSDPPass two subgraphs and a loss-less output list, 

41 breaking its grad-index contract. 

424. Communication-compute overlap: AutoOverlapPass, then FsdpOverlapPass 

43 (independent FSDP all-gather prefetch and gradient overlap). 

445. Pipeline split: PpPass runs last among the graph-level passes, after 

45 every graph-level pass. It replaces the joint graph with a schedule stub, 

46 moving the collectives into the schedule's per-stage submodules where a 

47 graph-level pass can no longer reach them. Running it last keeps the 

48 non-PP pass order untouched and still lets FsdpOverlapPass reorder the 

49 FSDP collectives before the split. 

506. Backend compilation: InductorPass is TERMINAL (``inductor_mode`` != off). 

51 It lowers the graph — or its tagged compute regions — to TorchInductor 

52 kernels; afterwards the FX graph is a wrapper around the compiled callable 

53 and no further graph-level pass may run. When PpPass already split the 

54 graph, the pass compiles each per-stage forward/backward subgraph owned by 

55 the installed schedule instead of the (compute-less) stub. 

567. NPU capture: ACLGraphPass wraps the final scheduled FX regions and keeps 

57 host work eager. It requires Inductor compilation and PP to be disabled. 

58""" 

59 

60__all__ = ["PassPipeline"] 

61 

62from typing import TYPE_CHECKING, Any, List, Optional 

63 

64from ..pass_config import PassConfig 

65from .activation_checkpoint import ActivationCheckpointPass 

66from .base import GraphPass 

67from .aclgraph_pass import ACLGraphPass 

68from .bucketing.bucketing_pass import FsdpBucketingPass 

69from .cpu_offload import CpuOffloadPass 

70from .inductor_pass import InductorPass 

71from .overlap.schedule import AutoOverlapPass, FsdpOverlapPass 

72from .parallel.fsdp_pass import FSDPPass 

73from .parallel.pp_pass import PpPass 

74 

75if TYPE_CHECKING: 

76 from torch import fx 

77 from ..graph_parallel_plan import GraphParallelPlan 

78 

79 

80class PassPipeline: 

81 """Pass Pipeline Orchestrator. 

82 

83 Automatically builds Pass execution order based on parallel configuration. 

84 """ 

85 

86 def __init__( 

87 self, 

88 pass_config: PassConfig, 

89 parallel_plan: Optional["GraphParallelPlan"] = None, 

90 ) -> None: 

91 """Initialize the pipeline with a parallel config and optional plan. 

92 

93 Args: 

94 pass_config: Parallel configuration driving pass selection. 

95 parallel_plan: Optional sharding plan forwarded to partitioning 

96 passes (e.g. ``FSDPPass``). 

97 """ 

98 self.config: PassConfig = pass_config 

99 self.parallel_plan = parallel_plan 

100 self.passes: List[GraphPass] = [] 

101 

102 def build(self) -> "PassPipeline": 

103 """Build Pass Pipeline.""" 

104 self.config.validate() 

105 # 1. Basic optimization 

106 self.passes.append(DeadCodeEliminationPass()) 

107 self.passes.append(CanonicalizeGraphPass()) 

108 

109 # 2. Activation checkpointing: recompute duplicates must exist while 

110 # the graph is still plain (no collectives yet), so FSDPPass inserts 

111 # parameter all-gathers / backward re-gathers around them. 

112 if self.config.ac_mode != "off": 

113 self.passes.append(ActivationCheckpointPass()) 

114 

115 # 2b. CPU offload: saved attention activations move to host memory. 

116 # Runs before FSDP so reload nodes are ordinary backward consumers when 

117 # parameter re-gathers are inserted. Attention swap is incompatible with 

118 # activation checkpointing, so AC never runs alongside this pass. 

119 if self.config.activation_swap != "none": 

120 self.passes.append(CpuOffloadPass()) 

121 

122 # 3. Execution layer: Parallel dimension partitioning 

123 if getattr(self.config, "fsdp_enabled", False): 

124 self.passes.append(FSDPPass(parallel_plan=self.parallel_plan)) 

125 if self.config.fsdp_bucketing: 

126 self.passes.append(FsdpBucketingPass()) 

127 

128 # 4. Communication-compute overlap optimization 

129 if getattr(self.config, "enable_overlap", False): 

130 self.passes.append(AutoOverlapPass()) 

131 if self.config.fsdp_allgather_prefetch or self.config.fsdp_overlap_grad_reduce: 

132 self.passes.append(FsdpOverlapPass()) 

133 

134 # 5. Pipeline split must run last: it replaces the joint graph with a 

135 # schedule stub, moving the collectives into the schedule's per-stage 

136 # submodules. Every graph-level pass (notably FsdpOverlapPass) must 

137 # therefore see the collectives before the split. 

138 if getattr(self.config, "pp_enabled", False): 

139 self.passes.append(PpPass(parallel_plan=self.parallel_plan)) 

140 

141 # 6. Terminal backend compilation: after this the FX graph wraps the 

142 # compiled callable and no further FX-graph-level pass may run. 

143 if self.config.inductor_mode != "off": 

144 self.passes.append(InductorPass()) 

145 

146 # Capture the final scheduled FX regions; replay bypasses Python nodes. 

147 if self.config.aclgraph_mode != "off": 

148 self.passes.append(ACLGraphPass()) 

149 

150 return self 

151 

152 def run( 

153 self, 

154 graph_module: "fx.GraphModule", 

155 **kwargs: Any, 

156 ) -> "fx.GraphModule": 

157 """Execute all Passes against ``graph_module`` using the pipeline's config. 

158 

159 The pipeline is built from a single ``PassConfig`` 

160 (``from_config`` / ``__init__``); that same config drives every 

161 pass. If a caller needs to run the same pipeline against a 

162 different config, build a new pipeline. 

163 

164 Args: 

165 graph_module: The FX GraphModule to transform. 

166 **kwargs: Extra keyword arguments forwarded to every pass 

167 (e.g. ``model`` / ``fsdp_group_name``). ``parallel_plan`` 

168 is auto-filled from the pipeline's plan when omitted. 

169 

170 Returns: 

171 The transformed graph module. 

172 """ 

173 # Ensure the parallel_plan is always available to passes that need 

174 # it (FSDPPass reads it from kwargs), even if the caller did not 

175 # pass it explicitly. 

176 if "parallel_plan" not in kwargs and self.parallel_plan is not None: 

177 kwargs["parallel_plan"] = self.parallel_plan 

178 

179 config = self.config 

180 for graph_pass in self.passes: 

181 graph_module = graph_pass.run(graph_module, config, **kwargs) 

182 return graph_module 

183 

184 @classmethod 

185 def from_config( 

186 cls, 

187 config: PassConfig, 

188 parallel_plan: Optional["GraphParallelPlan"] = None, 

189 ) -> "PassPipeline": 

190 """Create Pipeline from configuration. 

191 

192 Args: 

193 config: Parallel configuration driving pass selection. 

194 parallel_plan: Optional sharding plan forwarded to partitioning 

195 passes. 

196 

197 Returns: 

198 The built pipeline, ready to ``run``. 

199 """ 

200 return cls(config, parallel_plan).build() 

201 

202 

203class DeadCodeEliminationPass(GraphPass): 

204 """Dead code elimination Pass.""" 

205 

206 name = "dead_code_elimination" 

207 

208 def run( 

209 self, 

210 graph_module: "fx.GraphModule", 

211 pass_config: PassConfig, 

212 **kwargs: Any, 

213 ) -> "fx.GraphModule": 

214 """Eliminate dead nodes and recompile the graph. 

215 

216 Args: 

217 graph_module: The FX GraphModule to transform. 

218 pass_config: Parallel configuration (unused by this pass). 

219 **kwargs: Extra pass kwargs (unused). 

220 

221 Returns: 

222 The transformed graph module. 

223 """ 

224 graph_module.graph.eliminate_dead_code() 

225 graph_module.recompile() 

226 return graph_module 

227 

228 

229class CanonicalizeGraphPass(GraphPass): 

230 """Graph canonicalization Pass.""" 

231 

232 name = "canonicalize_graph" 

233 

234 def run( 

235 self, 

236 graph_module: "fx.GraphModule", 

237 pass_config: PassConfig, 

238 **kwargs: Any, 

239 ) -> "fx.GraphModule": 

240 """Lint and recompile the graph to a canonical form. 

241 

242 Args: 

243 graph_module: The FX GraphModule to transform. 

244 pass_config: Parallel configuration (unused by this pass). 

245 **kwargs: Extra pass kwargs (unused). 

246 

247 Returns: 

248 The transformed graph module. 

249 """ 

250 graph_module.graph.lint() 

251 graph_module.recompile() 

252 return graph_module