Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / attention.py: 59%

149 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"""Read native attention component source for visible forward patches. 

16 

17Expansion preserves the component's methods, QKV layout and kernel references. 

18Unchanged components remain native imports; the existing emitter expands source 

19only where a visible method rewrite requires it. CP dispatch and boundary 

20redistribution are emitted by their respective passes from native observations. 

21This source reader does not install runtime state or communication resources. 

22""" 

23 

24from __future__ import annotations 

25 

26import ast 

27import builtins 

28import inspect 

29from importlib.util import resolve_name 

30import symtable 

31import textwrap 

32from types import ModuleType 

33from typing import Any, Callable, Iterable 

34 

35from hyper_parallel.codegen.inline.expansion import ExpandedSource, expand_function 

36 

37 

38_FUSION_REPLACEMENT_NOTE = ( 

39 "# [HYPER INLINE] fused replacement for the original model's per-head\n" 

40 "# projections: q_proj/k_proj/v_proj are packed into a single linear_qkv\n" 

41 "# weight, whose checkpoint layout is converted via InterleaveQKV.\n" 

42) 

43 

44 

45def _fusion_replacement_note(class_name: str) -> str: 

46 """Annotate that the emitted fused module replaces the original projections. 

47 

48 The artifact keeps the real fused class (``linear_qkv`` takes over the 

49 weight the original model spread across ``q_proj``/``k_proj``/``v_proj``), 

50 so a reader of the generated model file sees a genuine class rather than a 

51 black-box substitution, with a comment naming what the fusion swallowed. 

52 """ 

53 return f"# [HYPER INLINE] {class_name}: {_FUSION_REPLACEMENT_NOTE}" 

54 

55 

56def _build_forward(module_type: type) -> ast.FunctionDef: 

57 """Derive forward from real source verbatim. 

58 

59 The body is the real ``forward`` exactly as written (its native 

60 ``self.attention_interface(...)`` call site is left completely unmodified). 

61 Neither CP nor TP orchestration is inlined here: the emitted boundary form 

62 redistributes around this forward, and the CP wrapper swaps 

63 ``attention_interface`` at install time — exactly as native's applier does 

64 at apply time. 

65 """ 

66 source = textwrap.dedent(inspect.getsource(module_type.forward)) 

67 tree = ast.parse(source) 

68 forward = tree.body[0] 

69 if not isinstance(forward, ast.FunctionDef) or forward.name != "forward": 

70 raise ValueError(f"codegen attention: {module_type.__name__}.forward is not a plain def") 

71 

72 _strip_annotations(forward) 

73 ast.fix_missing_locations(forward) 

74 return forward 

75 

76 

77def _strip_annotations(statement: ast.FunctionDef) -> None: 

78 """Drop type hints so the artifact has no import-time resolution burden. 

79 

80 Only annotations are cleared; ``*args`` and ``**kwargs`` parameters are kept 

81 because real forward bodies may reference them. 

82 """ 

83 statement.returns = None 

84 for arg in (*statement.args.posonlyargs, *statement.args.args, *statement.args.kwonlyargs): 

85 arg.annotation = None 

86 if statement.args.vararg is not None: 

87 statement.args.vararg.annotation = None 

88 if statement.args.kwarg is not None: 

89 statement.args.kwarg.annotation = None 

90 

91 

92def _drop_docstring(statement: ast.FunctionDef) -> None: 

93 """Drop a leading string-expression docstring from an emitted definition.""" 

94 if not statement.body: 

95 return 

96 first = statement.body[0] 

97 if ( 

98 isinstance(first, ast.Expr) 

99 and isinstance(first.value, ast.Constant) 

100 and isinstance(first.value.value, str) 

101 ): 

102 del statement.body[0] 

103 

104 

105def _referenced_global_names(source: str) -> set[str]: 

106 """Module-scope names ``source`` reads from every scope it defines. 

107 

108 ``symtable`` resolves the scopes, so parameters, locals, loop variables, 

109 comprehension targets and attribute accesses (``x.y`` contributes only 

110 ``x``) never show up as global reads. 

111 """ 

112 referenced: set[str] = set() 

113 pending = [symtable.symtable(source, "<codegen attention>", "exec")] 

114 while pending: 

115 table = pending.pop() 

116 referenced.update( 

117 symbol.get_name() 

118 for symbol in table.get_symbols() 

119 if symbol.is_global() and symbol.is_referenced() 

120 ) 

121 pending.extend(table.get_children()) 

122 return referenced 

123 

124 

125def _module_bound_names(source: str) -> set[str]: 

126 """Names the module-level statements of ``source`` bind.""" 

127 table = symtable.symtable(source, "<codegen attention>", "exec") 

128 return { 

129 symbol.get_name() 

130 for symbol in table.get_symbols() 

131 if symbol.is_assigned() or symbol.is_imported() or symbol.is_namespace() 

132 } 

133 

134 

135def _import_bound_names(lines: Iterable[str]) -> set[str]: 

136 """Names a sequence of ``import`` lines binds at module scope.""" 

137 names: set[str] = set() 

138 for line in lines: 

139 for alias in ast.parse(line).body[0].names: 

140 names.add(alias.asname or alias.name.split(".")[0]) 

141 return names 

142 

143 

144def _is_module_global(name: str) -> bool: 

145 """Whether ``name`` resolves in any module without an import of ours. 

146 

147 Builtins do, and so do dunders such as ``__name__``. A component definition 

148 of the same name wins over this: it is looked up first. 

149 """ 

150 return hasattr(builtins, name) or name.startswith("__") 

151 

152 

153def _owner_definitions(owner: ModuleType) -> dict[str, ast.stmt]: 

154 """Module-level definitions of the component's own module, by bound name.""" 

155 definitions: dict[str, ast.stmt] = {} 

156 for node in ast.parse(inspect.getsource(owner)).body: 

157 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): 

158 definitions[node.name] = node 

159 continue 

160 if isinstance(node, ast.Assign): 

161 targets: list[ast.expr] = list(node.targets) 

162 elif isinstance(node, ast.AnnAssign): 

163 targets = [node.target] 

164 else: 

165 continue 

166 for target in targets: 

167 if isinstance(target, ast.Name): 

168 definitions[target.id] = node 

169 return definitions 

170 

171 

172def _owner_import_lines(owner: ModuleType) -> dict[str, str]: 

173 """Import statement of the component's own module, per name it binds. 

174 

175 The artifact must import what the component's *module* imports (a re-export 

176 such as ``WeightConverter`` only exists under the path that module uses), so 

177 each line is copied from that module's own source rather than reconstructed 

178 from the value's ``__module__``. 

179 """ 

180 lines: dict[str, str] = {} 

181 for node in ast.parse(inspect.getsource(owner)).body: 

182 if isinstance(node, ast.Import): 

183 for alias in node.names: 

184 bound = alias.asname or alias.name.split(".")[0] 

185 line = f"import {alias.name}" + (f" as {alias.asname}" if alias.asname else "") 

186 lines.setdefault(bound, line) 

187 elif isinstance(node, ast.ImportFrom): 

188 module = (resolve_name("." * node.level + (node.module or ""), owner.__package__) 

189 if node.level else node.module) 

190 for alias in node.names: 

191 bound = alias.asname or alias.name 

192 line = f"from {module} import {alias.name}" + ( 

193 f" as {alias.asname}" if alias.asname else "" 

194 ) 

195 lines.setdefault(bound, line) 

196 return lines 

197 

198 

199def _definition_source(node: ast.stmt) -> str: 

200 """Copy one module-level definition, dropping hints and docstrings.""" 

201 if isinstance(node, ast.FunctionDef): 

202 _strip_annotations(node) 

203 _drop_docstring(node) 

204 return ast.unparse(node) 

205 

206 

207def _component_dependencies( 

208 module_type: type, code: str, *, provided: Iterable[str], inline_definitions: bool = True, 

209) -> tuple[str, tuple[str, ...]]: 

210 """Inline and import every name ``code`` reads from the component's module. 

211 

212 Copying a class body copies its references too, so a module-level helper 

213 added to the component after this renderer was written would be emitted as an 

214 undefined name. Each global name the copied code reads is therefore resolved 

215 against the component's own source module (``inspect.getmodule``, never an 

216 import of the component here): a module-level definition is inlined -- its own 

217 references first, so a helper referencing another helper completes the 

218 closure -- and a name that module imports is imported the same way. A name 

219 that resolves to neither fails generation rather than emitting an artifact 

220 with a latent ``NameError``. 

221 

222 Args: 

223 module_type: The real component whose source module is the access path. 

224 code: Emitted artifact text (the inlined class) to close over. 

225 provided: Names other emitted parts already bind in the artifact. 

226 inline_definitions: Copy local helpers, or retain their native module bindings. 

227 

228 Returns: 

229 The inlined definitions and the import lines the copied code needs. 

230 """ 

231 owner = inspect.getmodule(module_type) 

232 if owner is None: 

233 raise ValueError( 

234 f"codegen attention: cannot resolve the source module of {module_type.__name__!r}" 

235 ) 

236 definitions = _owner_definitions(owner) 

237 owner_imports = _owner_import_lines(owner) 

238 inlined: list[str] = [] 

239 imports: list[str] = [] 

240 resolved = set(provided) 

241 unresolved: list[str] = [] 

242 

243 def resolve(name: str) -> None: 

244 """Inline or import ``name``, or record it as unresolvable.""" 

245 if name in resolved: 

246 return 

247 node = definitions.get(name) 

248 if node is not None: 

249 if not inline_definitions: 

250 resolved.add(name) 

251 imports.append(f"from {owner.__name__} import {name}") 

252 return 

253 resolved.add(name) # before recursing: a helper may reference itself 

254 for dependency in sorted(_referenced_global_names(ast.unparse(node))): 

255 resolve(dependency) 

256 inlined.append(_definition_source(node)) 

257 return 

258 line = owner_imports.get(name) 

259 if line is not None: 

260 resolved.add(name) 

261 if line not in imports: 

262 imports.append(line) 

263 return 

264 if _is_module_global(name): 

265 resolved.add(name) 

266 return 

267 unresolved.append(name) 

268 

269 for name in sorted(_referenced_global_names(code)): 

270 resolve(name) 

271 if unresolved: 

272 raise ValueError( 

273 f"codegen attention: {module_type.__name__} references " 

274 f"{sorted(set(unresolved))} which neither {owner.__name__!r} defines nor " 

275 "imports; the generated class would carry an undefined name" 

276 ) 

277 return "\n\n\n".join(inlined), tuple(imports) 

278 

279 

280def _class_methods(module_type: type) -> list[ast.stmt]: 

281 """Copy every real method except ``forward``, dropping the module decorator.""" 

282 source = textwrap.dedent(inspect.getsource(module_type)) 

283 tree = ast.parse(source) 

284 for node in tree.body: 

285 if isinstance(node, ast.ClassDef) and node.name == module_type.__name__: 

286 methods = [ 

287 statement 

288 for statement in node.body 

289 if not ( 

290 isinstance(statement, ast.FunctionDef) and statement.name == "forward" 

291 ) 

292 ] 

293 for statement in methods: 

294 statement.decorator_list = [] 

295 if isinstance(statement, ast.FunctionDef): 

296 _strip_annotations(statement) 

297 return methods 

298 raise ValueError(f"codegen attention: no class {module_type.__name__!r} in its source module") 

299 

300 

301def render_attention_class(module_type: type, *, interface: Callable[..., Any]) -> ExpandedSource: 

302 """Render a self-contained attention class with a visible TP boundary. 

303 

304 The copied class methods and the module-level helpers they call are closed 

305 over the component's own source module, so the artifact carries everything it 

306 references: helpers are inlined and imports derived there, never listed here. 

307 

308 Args: 

309 module_type: The real grouped-query attention component (e.g. ``GroupedQueryAttentionModule``). 

310 interface: The attention kernel entry function to inline (e.g. 

311 ``run_qwen3_moe_flash_attention``); its closure is expanded into the 

312 artifact and it must stop at the hardware kernel. 

313 """ 

314 expanded_interface = expand_function(interface) 

315 forward = _build_forward(module_type) 

316 class_node = ast.ClassDef( 

317 name=module_type.__name__, 

318 bases=[ast.Name(id="nn.Module", ctx=ast.Load())], 

319 keywords=[], 

320 body=_class_methods(module_type) + [forward], 

321 decorator_list=[], 

322 ) 

323 built_class = _fusion_replacement_note(module_type.__name__) + ast.unparse(class_node) 

324 shared_defs = expanded_interface.source 

325 helpers, imports = _component_dependencies( 

326 module_type, 

327 built_class, 

328 provided=(_module_bound_names(shared_defs) | _import_bound_names(expanded_interface.imports)), 

329 ) 

330 return ExpandedSource( 

331 (*expanded_interface.imports, *imports), 

332 "\n\n\n".join(part for part in (helpers, shared_defs, built_class) if part), 

333 )