|
18 | 18 | from torch._sources import normalize_source_lines |
19 | 19 | from torch.fx import Graph, Tracer |
20 | 20 | from torch.fx.experimental.normalize import NormalizeArgs |
| 21 | +from torch.fx.node import Argument, Node, Target |
21 | 22 | from torch.fx.passes import shape_prop |
22 | 23 |
|
23 | 24 |
|
@@ -242,6 +243,42 @@ def trace( |
242 | 243 | rewritten = _rewrite(root, ast_rewriter_allow_list, self.leaf_module_list) |
243 | 244 | return super().trace(rewritten, concrete_args), rewritten |
244 | 245 |
|
| 246 | + # override TraceBase's method |
| 247 | + def create_node( |
| 248 | + self, |
| 249 | + kind: str, |
| 250 | + target: Target, |
| 251 | + args: Tuple[Argument, ...], |
| 252 | + kwargs: Dict[str, Argument], |
| 253 | + name: Optional[str] = None, |
| 254 | + type_expr: Optional[Any] = None, |
| 255 | + ) -> Node: |
| 256 | + """ |
| 257 | + Inserts a graph node given target, args, kwargs, and name. |
| 258 | +
|
| 259 | + This method can be overridden to do extra checking, validation, or |
| 260 | + modification of values used in node creation. For example, one might |
| 261 | + want to disallow in-place operations from being recorded. |
| 262 | + """ |
| 263 | + |
| 264 | + ## Hacky way to decide inplace ops |
| 265 | + if type(target) != str: |
| 266 | + name_target = target.__name__ |
| 267 | + else: |
| 268 | + name_target = target |
| 269 | + |
| 270 | + allow_list = ["and_", "or_"] # python operator.and_, operator.or_ |
| 271 | + if ( |
| 272 | + name_target[-1] == "_" |
| 273 | + and name_target[0] != "_" |
| 274 | + and not (name_target in allow_list) |
| 275 | + ): |
| 276 | + raise RuntimeError( |
| 277 | + f"Tried to trace mutable operation {name_target}. FX only supports functional code" |
| 278 | + ) |
| 279 | + |
| 280 | + return self.graph.create_node(kind, target, args, kwargs, name, type_expr) |
| 281 | + |
245 | 282 |
|
246 | 283 | # List of modules that need rewriting to be supported for tracing. |
247 | 284 | DEFAULT_REWRITE_ALLOW_LIST = { |
|
0 commit comments