|
| 1 | +import torch |
| 2 | +import torch.utils._pytree as pytree |
| 3 | +from torch import nn |
| 4 | +from typing import Callable, Optional, Dict |
| 5 | +from torch._functorch.aot_autograd import ( |
| 6 | + AOT_COUNTER, |
| 7 | + create_functional_call, |
| 8 | + create_aot_dispatcher_function, |
| 9 | + AOTConfig, |
| 10 | +) |
| 11 | +from torch._subclasses import FakeTensor |
| 12 | +from torch._functorch.partitioners import default_partition |
| 13 | + |
| 14 | + |
| 15 | +def aot_module( |
| 16 | + mod: nn.Module, |
| 17 | + args, |
| 18 | + fw_compiler: Callable, |
| 19 | + partition_fn: Callable = default_partition, |
| 20 | + decompositions: Optional[Dict] = None, |
| 21 | + keep_inference_input_mutations=False, |
| 22 | +) -> nn.Module: |
| 23 | + """ |
| 24 | + Adapted from: |
| 25 | + https://github.com/pytorch/pytorch/blob/cce2b7e3c95a7505b41bdfc53939d84d56e31260/torch/_functorch/aot_autograd.py#L3656-L3776 |
| 26 | +
|
| 27 | + This is the simplified or low overhead version of aot_module. For frontends |
| 28 | + like TorchDynamo, the input functions/modules to AOT are static and have |
| 29 | + unpacked inputs/outputs. This gives us an opportunity to remove the |
| 30 | + (1) pytree overhead to parse inputs/outputs, |
| 31 | + (2) AOT Autograd cache, |
| 32 | + (3) Reading of params/buffers in every forward call |
| 33 | +
|
| 34 | +
|
| 35 | + :func:`aot_module_simplified` removes these overheads. |
| 36 | + """ |
| 37 | + |
| 38 | + params = { |
| 39 | + **dict(mod.named_parameters(remove_duplicate=False)), |
| 40 | + **dict(mod.named_buffers(remove_duplicate=False)), |
| 41 | + } |
| 42 | + params_flat, params_spec = pytree.tree_flatten(params) |
| 43 | + params_flat = list(params_flat) |
| 44 | + params_len = len(params_flat) |
| 45 | + |
| 46 | + functional_call = create_functional_call(mod, params_spec, params_len) |
| 47 | + |
| 48 | + seen_sources = set() |
| 49 | + |
| 50 | + full_args = [] |
| 51 | + # First, the params |
| 52 | + full_args.extend(params_flat) |
| 53 | + |
| 54 | + if torch._guards.TracingContext.get(): |
| 55 | + torch._guards.TracingContext.get().params_flat = params_flat |
| 56 | + |
| 57 | + aot_autograd_arg_pos_to_source = None |
| 58 | + # Then, the params 1:1 mapped sources, if relevant. |
| 59 | + if hasattr(mod, "_param_name_to_source"): |
| 60 | + aot_autograd_arg_pos_to_source = [] |
| 61 | + # We now know this came from dynamo, and (1) we care about guards, |
| 62 | + # so setting up aot_autograd_arg_pos_to_source for downstream dedup guards |
| 63 | + # can now be done safely. (2) Dynamo logic protects the 1:1 sizing below. |
| 64 | + for name in params.keys(): |
| 65 | + assert name in mod._param_name_to_source, f"{name} not found." |
| 66 | + source = mod._param_name_to_source[name] |
| 67 | + assert source not in seen_sources, source |
| 68 | + seen_sources.add(source) |
| 69 | + aot_autograd_arg_pos_to_source.append(source) |
| 70 | + |
| 71 | + # Next, the input args |
| 72 | + full_args.extend(args) |
| 73 | + |
| 74 | + if hasattr(mod, "graph"): |
| 75 | + # Non dynamo entrypoints can get to here... |
| 76 | + for i, node in enumerate(mod.graph.nodes): |
| 77 | + if node.op == "placeholder": |
| 78 | + if hasattr(node, "_dynamo_source"): |
| 79 | + # ... but not here! |
| 80 | + if aot_autograd_arg_pos_to_source is None: |
| 81 | + aot_autograd_arg_pos_to_source = [] |
| 82 | + source = node._dynamo_source |
| 83 | + assert source not in seen_sources, source |
| 84 | + seen_sources.add(source) |
| 85 | + aot_autograd_arg_pos_to_source.append(source) |
| 86 | + |
| 87 | + if aot_autograd_arg_pos_to_source is not None: |
| 88 | + assert len(full_args) == len(aot_autograd_arg_pos_to_source) |
| 89 | + |
| 90 | + dynamic_shapes = False |
| 91 | + for x in full_args: |
| 92 | + if isinstance(x, FakeTensor): |
| 93 | + dynamic_shapes = x.fake_mode.shape_env is not None |
| 94 | + break |
| 95 | + |
| 96 | + aot_config = AOTConfig( |
| 97 | + fw_compiler=fw_compiler, |
| 98 | + bw_compiler=fw_compiler, |
| 99 | + inference_compiler=fw_compiler, |
| 100 | + partition_fn=partition_fn, |
| 101 | + decompositions=decompositions, |
| 102 | + num_params_buffers=params_len, |
| 103 | + aot_id=next(AOT_COUNTER), |
| 104 | + keep_inference_input_mutations=keep_inference_input_mutations, |
| 105 | + dynamic_shapes=dynamic_shapes, |
| 106 | + aot_autograd_arg_pos_to_source=aot_autograd_arg_pos_to_source, |
| 107 | + is_export=False, |
| 108 | + no_tangents=False, |
| 109 | + ) |
| 110 | + |
| 111 | + compiled_fn = create_aot_dispatcher_function( |
| 112 | + functional_call, |
| 113 | + full_args, |
| 114 | + aot_config, |
| 115 | + ) |
| 116 | + |
| 117 | + def forward(*runtime_args): |
| 118 | + full_args = [] |
| 119 | + full_args.extend(runtime_args) |
| 120 | + return compiled_fn(full_args) |
| 121 | + |
| 122 | + # Just for convenience |
| 123 | + forward.zero_grad = mod.zero_grad |
| 124 | + forward.named_parameters = mod.named_parameters |
| 125 | + forward.named_buffers = mod.named_buffers |
| 126 | + |
| 127 | + return forward |
0 commit comments