Instructions to use godlykmathews/BERT-Sentiment_Classifier with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use godlykmathews/BERT-Sentiment_Classifier with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="godlykmathews/BERT-Sentiment_Classifier")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("godlykmathews/BERT-Sentiment_Classifier", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload folder using huggingface_hub (part 16)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- venv/lib/python3.14/site-packages/torch/_functorch/aot_autograd.py +1952 -0
- venv/lib/python3.14/site-packages/torch/_functorch/apis.py +484 -0
- venv/lib/python3.14/site-packages/torch/_functorch/autograd_function.py +909 -0
- venv/lib/python3.14/site-packages/torch/_functorch/batch_norm_replacement.py +27 -0
- venv/lib/python3.14/site-packages/torch/_functorch/benchmark_utils.py +245 -0
- venv/lib/python3.14/site-packages/torch/_functorch/compile_utils.py +229 -0
- venv/lib/python3.14/site-packages/torch/_functorch/compilers.py +501 -0
- venv/lib/python3.14/site-packages/torch/_functorch/config.py +444 -0
- venv/lib/python3.14/site-packages/torch/_functorch/deprecated.py +188 -0
- venv/lib/python3.14/site-packages/torch/_functorch/eager_transforms.py +1951 -0
- venv/lib/python3.14/site-packages/torch/_functorch/functional_call.py +264 -0
- venv/lib/python3.14/site-packages/torch/_functorch/fx_minifier.py +562 -0
- venv/lib/python3.14/site-packages/torch/_functorch/make_functional.py +669 -0
- venv/lib/python3.14/site-packages/torch/_functorch/partitioners.py +0 -0
- venv/lib/python3.14/site-packages/torch/_functorch/predispatch.py +169 -0
- venv/lib/python3.14/site-packages/torch/_functorch/pyfunctorch.py +338 -0
- venv/lib/python3.14/site-packages/torch/_functorch/python_key.py +15 -0
- venv/lib/python3.14/site-packages/torch/_functorch/pytree_hacks.py +23 -0
- venv/lib/python3.14/site-packages/torch/_functorch/top_operators_github_usage.py +631 -0
- venv/lib/python3.14/site-packages/torch/_functorch/utils.py +40 -0
- venv/lib/python3.14/site-packages/torch/_functorch/vmap.py +567 -0
- venv/lib/python3.14/site-packages/torch/_guards.py +1536 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/__init__.py +86 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/_invoke_quant.py +61 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/aoti_call_delegate.py +165 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/associative_scan.py +923 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/auto_functionalize.py +1090 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/base_hop.py +281 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/cond.py +793 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/cudagraph_conditional_nodes.py +130 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/effects.py +340 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/executorch_call_delegate.py +182 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/flat_apply.py +183 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/flex_attention.py +1464 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/foreach_map.py +24 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/hints_wrap.py +142 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/inline_asm_elementwise.py +299 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/invoke_leaf_function.py +897 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/invoke_subgraph.py +1070 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/local_map.py +645 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/map.py +337 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/out_dtype.py +164 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/partitioner.py +380 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/passes/__init__.py +0 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/passes/inline_invoke_subgraph.py +69 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/print.py +153 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/run_const_graph.py +85 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/scan.py +994 -0
- venv/lib/python3.14/site-packages/torch/_higher_order_ops/schema.py +323 -0
.gitattributes
CHANGED
|
@@ -161,3 +161,5 @@ venv/lib/python3.14/site-packages/streamlit/static/static/media/SourceSerifVaria
|
|
| 161 |
venv/lib/python3.14/site-packages/streamlit/static/static/media/SourceSerifVariable-Roman.ttf.mdpVL9bi.woff2 filter=lfs diff=lfs merge=lfs -text
|
| 162 |
venv/lib/python3.14/site-packages/streamlit/static/static/media/fireworks.B4d-_KUe.gif filter=lfs diff=lfs merge=lfs -text
|
| 163 |
venv/lib/python3.14/site-packages/tokenizers/tokenizers.abi3.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 161 |
venv/lib/python3.14/site-packages/streamlit/static/static/media/SourceSerifVariable-Roman.ttf.mdpVL9bi.woff2 filter=lfs diff=lfs merge=lfs -text
|
| 162 |
venv/lib/python3.14/site-packages/streamlit/static/static/media/fireworks.B4d-_KUe.gif filter=lfs diff=lfs merge=lfs -text
|
| 163 |
venv/lib/python3.14/site-packages/tokenizers/tokenizers.abi3.so filter=lfs diff=lfs merge=lfs -text
|
| 164 |
+
venv/lib/python3.14/site-packages/torch/bin/protoc filter=lfs diff=lfs merge=lfs -text
|
| 165 |
+
venv/lib/python3.14/site-packages/torch/bin/protoc-3.13.0.0 filter=lfs diff=lfs merge=lfs -text
|
venv/lib/python3.14/site-packages/torch/_functorch/aot_autograd.py
ADDED
|
@@ -0,0 +1,1952 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import itertools
|
| 5 |
+
import time
|
| 6 |
+
from contextlib import nullcontext
|
| 7 |
+
from functools import wraps
|
| 8 |
+
from typing import Any, Literal, TYPE_CHECKING
|
| 9 |
+
from typing_extensions import ParamSpec, TypeVar
|
| 10 |
+
from unittest.mock import patch
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch._dynamo.logging
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import torch.utils._pytree as pytree
|
| 16 |
+
import torch.utils.dlpack
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
from torch._decomp.decompositions_for_rng import PhiloxStateTracker, rng_decompositions
|
| 19 |
+
from torch._dispatch.python import enable_python_dispatcher
|
| 20 |
+
from torch._dynamo import compiled_autograd
|
| 21 |
+
from torch._dynamo.utils import (
|
| 22 |
+
CompileEventLogger,
|
| 23 |
+
dynamo_timed,
|
| 24 |
+
preserve_rng_state,
|
| 25 |
+
set_feature_use,
|
| 26 |
+
)
|
| 27 |
+
from torch._guards import detect_fake_mode
|
| 28 |
+
from torch._inductor.codecache import resolve_pre_grad_pass_timing
|
| 29 |
+
|
| 30 |
+
# Runtime annotation consumers still resolve BoxedBool from module globals.
|
| 31 |
+
from torch._subclasses import FakeTensor, FakeTensorMode
|
| 32 |
+
from torch.export._tree_utils import reorder_kwargs
|
| 33 |
+
from torch.fx.experimental.proxy_tensor import make_fx
|
| 34 |
+
|
| 35 |
+
from . import config
|
| 36 |
+
from ._aot_autograd import autograd_cache
|
| 37 |
+
from ._aot_autograd.autograd_cache import ( # noqa: F401
|
| 38 |
+
AOTAutogradCache,
|
| 39 |
+
should_use_local_autograd_cache,
|
| 40 |
+
should_use_remote_autograd_cache,
|
| 41 |
+
)
|
| 42 |
+
from ._aot_autograd.collect_metadata_analysis import ( # noqa: F401
|
| 43 |
+
run_functionalized_fw_and_collect_metadata,
|
| 44 |
+
)
|
| 45 |
+
from ._aot_autograd.descriptors import (
|
| 46 |
+
AOTInput,
|
| 47 |
+
BufferAOTInput,
|
| 48 |
+
DifferentiableAOTInput,
|
| 49 |
+
ParamAOTInput,
|
| 50 |
+
PlainAOTInput,
|
| 51 |
+
)
|
| 52 |
+
from ._aot_autograd.frontend_utils import (
|
| 53 |
+
_detect_attribute_assignment,
|
| 54 |
+
_try_get_metadata_from_dynamo,
|
| 55 |
+
construct_fake_mode,
|
| 56 |
+
process_inputs,
|
| 57 |
+
)
|
| 58 |
+
from ._aot_autograd.functional_utils import ( # noqa: F401
|
| 59 |
+
_check_if_mutation_can_be_in_graph,
|
| 60 |
+
are_all_mutations_hidden_from_autograd,
|
| 61 |
+
are_all_mutations_under_no_grad_or_inference_mode,
|
| 62 |
+
assert_functional_graph,
|
| 63 |
+
from_fun,
|
| 64 |
+
gen_alias_from_base,
|
| 65 |
+
has_data_mutation,
|
| 66 |
+
has_metadata_mutation,
|
| 67 |
+
is_fun,
|
| 68 |
+
sync_functional_tensor,
|
| 69 |
+
to_fun,
|
| 70 |
+
)
|
| 71 |
+
from ._aot_autograd.graph_capture_wrappers import ( # noqa: F401
|
| 72 |
+
aot_dispatch_subclass,
|
| 73 |
+
create_functional_call,
|
| 74 |
+
create_functionalized_fn,
|
| 75 |
+
create_functionalized_rng_ops_wrapper,
|
| 76 |
+
create_joint,
|
| 77 |
+
fn_input_mutations_to_outputs,
|
| 78 |
+
fn_prepped_for_autograd,
|
| 79 |
+
)
|
| 80 |
+
from ._aot_autograd.graph_compile import ( # noqa: F401
|
| 81 |
+
aot_stage1_graph_capture,
|
| 82 |
+
aot_stage2_compile,
|
| 83 |
+
aot_stage2_export,
|
| 84 |
+
)
|
| 85 |
+
from ._aot_autograd.input_output_analysis import ( # noqa: F401
|
| 86 |
+
compute_overlapping_inputs,
|
| 87 |
+
create_graph_signature,
|
| 88 |
+
create_synthetic_base_metadata,
|
| 89 |
+
remove_dupe_metadata,
|
| 90 |
+
)
|
| 91 |
+
from ._aot_autograd.logging_utils import ( # noqa: F401
|
| 92 |
+
callback_set,
|
| 93 |
+
describe_input,
|
| 94 |
+
format_guard_bug_msg,
|
| 95 |
+
get_aot_compilation_context,
|
| 96 |
+
get_aot_graph_name,
|
| 97 |
+
get_graph_being_compiled,
|
| 98 |
+
graph_being_compiled,
|
| 99 |
+
model_name,
|
| 100 |
+
nth_graph,
|
| 101 |
+
set_model_name,
|
| 102 |
+
setup_stacktrace_preservation_hooks,
|
| 103 |
+
track_graph_compiling,
|
| 104 |
+
)
|
| 105 |
+
from ._aot_autograd.runtime_wrappers import ( # noqa: F401
|
| 106 |
+
AOTDedupeWrapper,
|
| 107 |
+
AOTSyntheticBaseWrapper,
|
| 108 |
+
SerializableCompiledFunction,
|
| 109 |
+
)
|
| 110 |
+
from ._aot_autograd.schemas import ( # noqa: F401
|
| 111 |
+
AOTConfig,
|
| 112 |
+
AOTDispatchCompiler,
|
| 113 |
+
AOTGraphCapture,
|
| 114 |
+
AOTState,
|
| 115 |
+
BackwardSignature,
|
| 116 |
+
FakifiedFlatArgs,
|
| 117 |
+
FQN,
|
| 118 |
+
GraphInputName,
|
| 119 |
+
GraphOutputName,
|
| 120 |
+
GraphSignature,
|
| 121 |
+
InputAliasInfo,
|
| 122 |
+
JointWithDescriptors,
|
| 123 |
+
MutationType,
|
| 124 |
+
OpaqueMeta,
|
| 125 |
+
OutputAliasInfo,
|
| 126 |
+
OutputType,
|
| 127 |
+
SerializableAOTDispatchCompiler,
|
| 128 |
+
SubclassCreationMeta,
|
| 129 |
+
SubclassMeta,
|
| 130 |
+
TensorAlias,
|
| 131 |
+
ViewAndMutationMeta,
|
| 132 |
+
)
|
| 133 |
+
from ._aot_autograd.subclass_utils import ( # noqa: F401
|
| 134 |
+
requires_subclass_dispatch,
|
| 135 |
+
unwrap_tensor_subclasses,
|
| 136 |
+
unwrap_tensor_subclasses_with_indices_to_original,
|
| 137 |
+
wrap_tensor_subclasses,
|
| 138 |
+
wrap_tensor_subclasses_maybe_joint,
|
| 139 |
+
)
|
| 140 |
+
from ._aot_autograd.utils import ( # noqa: F401
|
| 141 |
+
_get_autocast_states,
|
| 142 |
+
call_func_at_runtime_with_args,
|
| 143 |
+
create_tree_flattened_fn,
|
| 144 |
+
KNOWN_TYPES,
|
| 145 |
+
make_boxed_compiler,
|
| 146 |
+
make_boxed_func,
|
| 147 |
+
maybe_to_fresh_input,
|
| 148 |
+
normalize_as_list,
|
| 149 |
+
partial_flatten_asdict,
|
| 150 |
+
PytreeThunk,
|
| 151 |
+
root_module_when_exporting_non_strict,
|
| 152 |
+
simple_wraps,
|
| 153 |
+
strict_zip,
|
| 154 |
+
)
|
| 155 |
+
from .partitioners import default_partition
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
if TYPE_CHECKING:
|
| 159 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 160 |
+
|
| 161 |
+
from torch._inductor.compile_fx import CompilerConfigExtra
|
| 162 |
+
from torch._inductor.output_code import OutputCode
|
| 163 |
+
from torch._inductor.utils import InputType
|
| 164 |
+
from torch._ops import OpOverload
|
| 165 |
+
from torch.fx.experimental.symbolic_shapes import ShapeEnv
|
| 166 |
+
|
| 167 |
+
_P = ParamSpec("_P")
|
| 168 |
+
_R = TypeVar("_R")
|
| 169 |
+
|
| 170 |
+
zip = strict_zip
|
| 171 |
+
|
| 172 |
+
# This global counter increments every time we compile a graph with
|
| 173 |
+
# AOTAutograd. You can use this to correlate runtime error messages
|
| 174 |
+
# with compile time (e.g., if you get an error at runtime saying
|
| 175 |
+
# compiled graph 3 failed, you can set a breakpoint at compile time
|
| 176 |
+
# for this graph number to investigate further at compile time.)
|
| 177 |
+
#
|
| 178 |
+
# NB: this is different from get_aot_compilation_context, which tracks
|
| 179 |
+
# each underlying graph that is compiled. In contrast, AOT_COUNTER
|
| 180 |
+
# corresponds to top-level invocations of aot_module/aot_function;
|
| 181 |
+
# one counter is allocated per entire compiled block (but this block
|
| 182 |
+
# may involve compiling multiple subgraphs; e.g., for forwards/backwards)
|
| 183 |
+
AOT_COUNTER = itertools.count()
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 187 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 188 |
+
#
|
| 189 |
+
# AOT Autograd contains a pretty non-trivial amount of logic to handle edge cases around aliasing and mutation
|
| 190 |
+
# that are external to the graph (they show up as side effects in some way when you run the graph).
|
| 191 |
+
#
|
| 192 |
+
# Take a look at `test_aotdispatch.py TestAOTAutograd.test_input_mutation*` tests for some examples functions
|
| 193 |
+
# and what they're compiled graphs looks like.
|
| 194 |
+
# Below is a very long comment detailing several edge cases, and showing how AOT Autograd handles them.
|
| 195 |
+
#
|
| 196 |
+
# Note [AOT Autograd: input data mutations]
|
| 197 |
+
#
|
| 198 |
+
# If we compile a function that mutates inputs, then those input mutations are real side effects
|
| 199 |
+
# that a user expects to see after running the compiled graph.
|
| 200 |
+
# However, the graph that we want to send to a backend needs to be *entirely* functional.
|
| 201 |
+
# The way we reconcile this difference is that we remove the mutations completely from the graph that we compile
|
| 202 |
+
# but we update the graph to return (updated_inputs, user_outputs).
|
| 203 |
+
# In the epilogue that runs after the compiled graph is executed, we copy the updated inputs back to the originals.
|
| 204 |
+
#
|
| 205 |
+
# Example: original user code:
|
| 206 |
+
# def f(x):
|
| 207 |
+
# x.mul_(2)
|
| 208 |
+
# out = x.mul(3)
|
| 209 |
+
# return out
|
| 210 |
+
#
|
| 211 |
+
# After AOT Autograd compiles, we end up with a:
|
| 212 |
+
# (a) compiled graph
|
| 213 |
+
# (b) autograd.Function.forward() method, that executes the compiled graph
|
| 214 |
+
# (c) wrapper function, that calls the autograd.Function.forward() and performs the epilogue
|
| 215 |
+
#
|
| 216 |
+
# The output of (a, b, c) are all written below.
|
| 217 |
+
#
|
| 218 |
+
# def compiled_forward_graph(x):
|
| 219 |
+
# x_updated = x.mul(2)
|
| 220 |
+
# out = x_updated.mul(3)
|
| 221 |
+
# return x_updated, out
|
| 222 |
+
#
|
| 223 |
+
# # x_updated gets a gradient in the compiled backward
|
| 224 |
+
# def compiled_backward_graph(grad_x_updated, grad_out):
|
| 225 |
+
# grad_x = ...
|
| 226 |
+
# return grad_x
|
| 227 |
+
#
|
| 228 |
+
# def autograd.Function.forward(x):
|
| 229 |
+
# x_updated, out = compiled_forward_graph(x)
|
| 230 |
+
# return x_updated, out
|
| 231 |
+
#
|
| 232 |
+
# def compiled_wrapper(x):
|
| 233 |
+
# x_updated, out = autograd.Function.apply(x)
|
| 234 |
+
# x.copy_(x_updated)
|
| 235 |
+
# return out
|
| 236 |
+
#
|
| 237 |
+
# Another important thing to note is that updated inputs (due to data mutations) *do* participate
|
| 238 |
+
# in the compiled backward graph! Since the compiled forward graph gets N extra outputs
|
| 239 |
+
# (due to updated inputs showing up as graph outputs),
|
| 240 |
+
# The compiled backward gets an additional N inputs.
|
| 241 |
+
# That way, during the x.copy_(x_updated) bit in the epilogue, gradients will flow from the updated input
|
| 242 |
+
# back to the original input.
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# Note [AOT Autograd: input metadata mutations]
|
| 246 |
+
#
|
| 247 |
+
# For the same reason as input mutations, we also don't put input metadata mutations in the graph.
|
| 248 |
+
# Instead, we return the updated version of the input (a view), and mutate the input's metadata outside of the graph
|
| 249 |
+
#
|
| 250 |
+
# Example: original user code:
|
| 251 |
+
# def f(x):
|
| 252 |
+
# x.t_()
|
| 253 |
+
# out = x.mul(3)
|
| 254 |
+
# return out
|
| 255 |
+
#
|
| 256 |
+
# AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function):
|
| 257 |
+
# def compiled_forward_graph(x):
|
| 258 |
+
# x_updated = x.t()
|
| 259 |
+
# out = x_updated.mul(3)
|
| 260 |
+
# return x_updated, out
|
| 261 |
+
#
|
| 262 |
+
# # x_updated does *not* get a gradient in the compiled backward
|
| 263 |
+
# def compiled_backward_graph(grad_out):
|
| 264 |
+
# grad_x = ...
|
| 265 |
+
# return grad_x
|
| 266 |
+
#
|
| 267 |
+
# def autograd.Function.forward(x):
|
| 268 |
+
# x_updated, out = compiled_forward_graph(x)
|
| 269 |
+
# return x_updated, out
|
| 270 |
+
#
|
| 271 |
+
# def compiled_wrapper(x):
|
| 272 |
+
# x_updated, out = autograd.Function.apply(x)
|
| 273 |
+
# x.as_strided_(x_updated)
|
| 274 |
+
# return out
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
# Note [AOT Autograd: outputs aliasing inputs or intermediates!]
|
| 278 |
+
#
|
| 279 |
+
# AOT Autograd needs special handling for outputs that alias graph inputs or intermediates!
|
| 280 |
+
# Why?
|
| 281 |
+
# (1) autograd.Function.forward() has a limitation, where views that returned in the forward cannot later be mutated.
|
| 282 |
+
# (2) views don't need to be compiled in the graph anyway - it's cheap to generate them outside of the compiled graph,
|
| 283 |
+
# in an epilogue.
|
| 284 |
+
# For outputs that alias inputs, we do the following:
|
| 285 |
+
# (a) *still* return the aliased output as a graph output
|
| 286 |
+
# (b) In the AOT Autograd wrapper/epilogue, we don't return that aliased output. Instead, we use it to regenerate the output.
|
| 287 |
+
#
|
| 288 |
+
# For outputs that alias *intermediates*, we do the following:
|
| 289 |
+
# (a) Return the output in the compiled forward, **and** return it's ._base (a graph intermediates) as an output in the forward
|
| 290 |
+
# (b) Use (output, graph_intermediate) to regenerate the alias, and return that to the user (instead of the compiled fw output).
|
| 291 |
+
# You might wonder why we return the aliased output directly in the graph (and making the graph compute it),
|
| 292 |
+
# only to not return it and instead generate a fresh alias off of the intermediate,
|
| 293 |
+
# instead of (say) just storing metadata about the size/stride of the output somewhere to generate the alias. There are two reasons:
|
| 294 |
+
# (1) Getting the actual alias tensor allows us to use view-replay to generate the alias, instead of an as_strided() call
|
| 295 |
+
# (2) Inductor (and other backends) are free to change the memory format of graph outputs, if it results in better performance.
|
| 296 |
+
# This can result in problems if a user later tries to .view() that output expecting it to have one set of strides,
|
| 297 |
+
# when it has a different set of strides.
|
| 298 |
+
# By including the view op directly in the graph, inductor takes that into account when deciding what memory format
|
| 299 |
+
# the graph intermediate should be.
|
| 300 |
+
#
|
| 301 |
+
# Another important thing to note is how our traced backward() graph handles aliases.
|
| 302 |
+
# (this applies to outputs aliasing inputs, outputs aliasing intermediates,
|
| 303 |
+
# *and* updated inputs returned in the compiled forward due to metadata-only mutations).
|
| 304 |
+
# Any outputs that alias (either inputs or intermediates) do NOT participate in the compiled backward graph
|
| 305 |
+
# It would be wasteful to include them in the compiled backward(), because we regenerate them eagerly
|
| 306 |
+
# at the end of the forward.
|
| 307 |
+
#
|
| 308 |
+
# Example: original user code:
|
| 309 |
+
# def f(x):
|
| 310 |
+
# out1 = x.t()
|
| 311 |
+
# intermediate = x.mul(2)
|
| 312 |
+
# out2 = intermediate.view(-1)
|
| 313 |
+
# return out1, out2
|
| 314 |
+
#
|
| 315 |
+
# AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function):
|
| 316 |
+
# def compiled_forward_graph(x):
|
| 317 |
+
# out1 = x.t()
|
| 318 |
+
# intermediate = x.mul(2)
|
| 319 |
+
# out2 = intermediate.view(-1)
|
| 320 |
+
# # the compiled graph also returns the intermediate
|
| 321 |
+
# return out1, out2, intermediate
|
| 322 |
+
#
|
| 323 |
+
# # intermediate gets a gradient in the compiled backward.
|
| 324 |
+
# # both output aliases (out1 and out2) do not.
|
| 325 |
+
# def compiled_backward_graph(grad_intermediate):
|
| 326 |
+
# grad_x = ...
|
| 327 |
+
# return grad_x
|
| 328 |
+
#
|
| 329 |
+
# def autograd.Function.forward(x):
|
| 330 |
+
# out1, out2, intermediate = compiled_forward_graph(x)
|
| 331 |
+
# return out1, out2, intermediate
|
| 332 |
+
#
|
| 333 |
+
# def compiled_wrapper(x):
|
| 334 |
+
# out1, out2, intermediate = autograd.Function.apply(x)
|
| 335 |
+
# # regenerate out1 from the input
|
| 336 |
+
# out1_regenerated = out1._view_func(x)
|
| 337 |
+
# # regenerate out1 from the intermediate
|
| 338 |
+
# out2_regenerated = out2._view_func(intermediate)
|
| 339 |
+
# return out1_regenerated, out2_regenerated
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# Note [AOT Autograd: mutations to inputs that alias other inputs]
|
| 343 |
+
#
|
| 344 |
+
# Another edge case that is (only partially) handled today is when an input is mutated, but itself aliases another input.
|
| 345 |
+
# AOT Autograd needs to **ensure** that functionalization knows that the two inputs are aliased to each other.
|
| 346 |
+
# That way, when the aliased input is accessed later in the graph, functionalization knows to "update" the alias
|
| 347 |
+
# given the mutation that occurred.
|
| 348 |
+
#
|
| 349 |
+
# This is handled by updating the calling convention: we create a "synthetic base" that becomes a new input
|
| 350 |
+
# in the compiled function, and we regenerate the original (aliased) inputs directly off of the base
|
| 351 |
+
# inside of the compiled function.
|
| 352 |
+
#
|
| 353 |
+
# This logic is fully encapsulated in aot_wrapper_synthetic_base()
|
| 354 |
+
#
|
| 355 |
+
# Example: original user code:
|
| 356 |
+
# def f(x, x_view):
|
| 357 |
+
# x.mul_(2)
|
| 358 |
+
# out = x * x_view
|
| 359 |
+
# return out
|
| 360 |
+
# f(x, x.view(-1))
|
| 361 |
+
#
|
| 362 |
+
# AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function):
|
| 363 |
+
# def compiled_forward_graph(base)
|
| 364 |
+
# x = generate_x(base)
|
| 365 |
+
# x_view = generate_x_view(base)
|
| 366 |
+
# x_updated = x.mul(2)
|
| 367 |
+
# x_view_updated = x_updated.view(-1)
|
| 368 |
+
# out = x_updated * x_view_updated
|
| 369 |
+
# return x_updated, out
|
| 370 |
+
#
|
| 371 |
+
# # The calling convention change from (aliases) -> (base) happens
|
| 372 |
+
# # *outside* of the autograd.Function.forward().
|
| 373 |
+
# # That means the forward() only has 1 input (base),
|
| 374 |
+
# # and the backward() only has 1 output (grad_base)
|
| 375 |
+
# def compiled_backward_graph(grad_out):
|
| 376 |
+
# grad_base = ...
|
| 377 |
+
# return grad_base
|
| 378 |
+
#
|
| 379 |
+
# def autograd.Function.forward(base):
|
| 380 |
+
# x_updated, out = compiled_forward_graph(base)
|
| 381 |
+
# return x_updated, out
|
| 382 |
+
#
|
| 383 |
+
# # The compiled wrapper is where we create synthetic bases.
|
| 384 |
+
# # The info on which inputs are mutated is also tracked *before* synthetic base creation.
|
| 385 |
+
# def compiled_wrapper(x, x_view):
|
| 386 |
+
# base = merge_view_inputs(x, x_view)
|
| 387 |
+
# x_updated, out = autograd.Function.apply(base)
|
| 388 |
+
# # x and x_view are aliased in eager mode, so this mutation to x will automatically affect x_view.
|
| 389 |
+
# x.copy_(x_updated)
|
| 390 |
+
# return out
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
# Note [AOT Autograd: Views to avoid tangents aliasing inputs]
|
| 394 |
+
#
|
| 395 |
+
# We view every forward output when creating out tangent tensors to handle the problematic
|
| 396 |
+
# case in which a subclass does extra aliasing between graph outputs/inputs in a way that
|
| 397 |
+
# is not visible above the subclass.
|
| 398 |
+
#
|
| 399 |
+
# Ordinarily, when constructing the joint function that we want to trace in AOTAutograd,
|
| 400 |
+
# we're guaranteed that the tangent tensors that we pass
|
| 401 |
+
# into the joint are distinct tensors from the primals. This is because when
|
| 402 |
+
# decide which forward outputs to create tangents for, we only create tangents
|
| 403 |
+
# for forward outputs that are not aliases of inputs (See Note
|
| 404 |
+
# [AOT Autograd: outputs aliasing inputs or intermediates!]).
|
| 405 |
+
#
|
| 406 |
+
# However, when wrapper tensor subclasses enter the picture, it is possible
|
| 407 |
+
# to have an output of the forward that is a subclass that is not an
|
| 408 |
+
# input / alias of an input, but one of its inner tensors is an alias!
|
| 409 |
+
# NestedTensor is an example: Performing an out-of-place pointwise op on a
|
| 410 |
+
# NestedTensor constructs a fresh NestedTensor that holds onto the input's
|
| 411 |
+
# offsets tensor directly.
|
| 412 |
+
#
|
| 413 |
+
# Having tangent tensors that are the same as the (primal) forward inputs,
|
| 414 |
+
# can cause problems during tracing as make_fx() will specialize on our
|
| 415 |
+
# duplicate inputs: If we passed in the same tensor for primals_1 and
|
| 416 |
+
# tangents_1 during tracing, make_fx() will happily sub out all usages of
|
| 417 |
+
# tangents_1 with primals_1 in the graph, which is not what we want.
|
| 418 |
+
#
|
| 419 |
+
# To work around this, we view every forward output when creating out tangent
|
| 420 |
+
# tensors so that tangents can never be the same as forward inputs even if
|
| 421 |
+
# forward inputs alias forward outputs.
|
| 422 |
+
|
| 423 |
+
# Note [Side-Effectful Tokens in AOTAutograd]
|
| 424 |
+
#
|
| 425 |
+
# We allow some some side-effectful operators in
|
| 426 |
+
# the post-AOTAutograd (functional) graph, such as prints and torchbind operations.
|
| 427 |
+
# To ensure that these side-effects are compatible to future graph passes that
|
| 428 |
+
# assume that the graph is functional, we will thread "effect tokens" to show
|
| 429 |
+
# data dependence between these side-effectful operators. Practically speaking,
|
| 430 |
+
# effect tokens are just dummy values (torch.tensor([])). The graph would look
|
| 431 |
+
# like the following:
|
| 432 |
+
#
|
| 433 |
+
# def gm(self, token0, reader):
|
| 434 |
+
# token1, frame = with_token(ordered_effect_op, (reader,), token0)
|
| 435 |
+
# frame = frame * 2
|
| 436 |
+
# token2, frame2 = with_token(ordered_effect_op, (reader,), token1)
|
| 437 |
+
# frame2 = frame2 * 2
|
| 438 |
+
# return token2, frame, frame2
|
| 439 |
+
#
|
| 440 |
+
# We will pass the token as an input to the graph, thread it through
|
| 441 |
+
# side-effectful operators using the `with_effects` high order operator, and then
|
| 442 |
+
# return the updated token as an output.
|
| 443 |
+
# So the signature of the graph input would look something like
|
| 444 |
+
# (*tokens, *params_buffers, *user_inputs), and the signature of the graph
|
| 445 |
+
# output would look something like (*tokens, *outputs).
|
| 446 |
+
#
|
| 447 |
+
# However, Inductor does not want the concept of tokens in the final generated
|
| 448 |
+
# code's input and output. Since changing the graph signature inside of inductor
|
| 449 |
+
# is difficult, after generating the forward graph, we will run a pass to
|
| 450 |
+
# remove the tokens from the inputgenerate the following graph for Inductor, where
|
| 451 |
+
# the tokens are created and sunk within the graph, rather than as inputs and
|
| 452 |
+
# outputs:
|
| 453 |
+
#
|
| 454 |
+
# def gm(self, reader):
|
| 455 |
+
# token0 = torch.ops.prims._make_token()
|
| 456 |
+
# token1, frame = with_token(ordered_effect_op, (reader,), token0)
|
| 457 |
+
# frame = frame * 2
|
| 458 |
+
# token2, frame2 = with_token(ordered_effect_op, (reader,), token1)
|
| 459 |
+
# frame2 = frame2 * 2
|
| 460 |
+
# sink_token = torch.ops.prims._sink_tokens([token2])
|
| 461 |
+
# return frame, frame2
|
| 462 |
+
|
| 463 |
+
#
|
| 464 |
+
#
|
| 465 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 466 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
aot_autograd_decompositions: dict[OpOverload, Callable[..., Any]] = {}
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def create_aot_state(
|
| 473 |
+
stack: contextlib.ExitStack,
|
| 474 |
+
flat_fn: Callable[_P, _R],
|
| 475 |
+
fake_flat_args: FakifiedFlatArgs,
|
| 476 |
+
flat_args_descs: list[AOTInput],
|
| 477 |
+
aot_config: AOTConfig,
|
| 478 |
+
fake_mode: FakeTensorMode,
|
| 479 |
+
shape_env: ShapeEnv | None,
|
| 480 |
+
) -> AOTState:
|
| 481 |
+
"""
|
| 482 |
+
Traces the forward and backward graphs of the attr:`flat_fn` to generate a
|
| 483 |
+
joint graph. The joint graph is an Fx graph with Aten ops. Please refer to
|
| 484 |
+
the tracing mechanism to understand the graph capturing details.
|
| 485 |
+
|
| 486 |
+
The joint graph is then passed through attr:`partition_fn` to isolate the
|
| 487 |
+
forward and backward portions, which are then respectively compiled via the
|
| 488 |
+
provided attr:`fw_compiler` and attr:`bw_compiler`.
|
| 489 |
+
|
| 490 |
+
The resulting compiled forward and backward graphs are then wrapped up in a
|
| 491 |
+
``torch.autograd.Function`` object.
|
| 492 |
+
|
| 493 |
+
The calling convention here is that the first aot_config.num_params_buffers
|
| 494 |
+
inputs in flat_args are parameters and buffers, and the rest are inputs.
|
| 495 |
+
|
| 496 |
+
We use this to assume that parameters/buffer's shapes don't change.
|
| 497 |
+
"""
|
| 498 |
+
|
| 499 |
+
# Old name for now to avoid messing with stats. Also, note this is pushed
|
| 500 |
+
# on the stack, so it extends BEYOND this function
|
| 501 |
+
stack.enter_context(
|
| 502 |
+
dynamo_timed("create_aot_dispatcher_function", log_pt2_compile_event=True)
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
# This is the main entry point.
|
| 506 |
+
# TODO: Chillee argues that dynamo itself should pass in fake tensors to
|
| 507 |
+
# the list of arguments when compiling; at the moment we do not do this
|
| 508 |
+
|
| 509 |
+
if aot_config.decompositions is None:
|
| 510 |
+
aot_config.decompositions = {}
|
| 511 |
+
|
| 512 |
+
aot_config.decompositions = {
|
| 513 |
+
**aot_autograd_decompositions,
|
| 514 |
+
**aot_config.decompositions,
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
if config.functionalize_rng_ops:
|
| 518 |
+
# Update the decompositions with functionalized random decompositions
|
| 519 |
+
aot_config.decompositions = { # type: ignore[assignment]
|
| 520 |
+
**rng_decompositions,
|
| 521 |
+
**aot_config.decompositions,
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
# Check flat_args to see if they're already fake. If so, use that fake
|
| 525 |
+
# mode instead.
|
| 526 |
+
|
| 527 |
+
python_dispatcher_mode = (
|
| 528 |
+
enable_python_dispatcher() if shape_env is not None else nullcontext()
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
# See NOTE: [Deferring tensor pack/unpack hooks until runtime]
|
| 532 |
+
# If any saved tensor hooks are active, we **don't** want to trace them.
|
| 533 |
+
# Instead, we'll let them run at runtime, around the custom autograd.Function
|
| 534 |
+
# that we generate in torch.compile.
|
| 535 |
+
stack.enter_context(torch.autograd.set_multithreading_enabled(False))
|
| 536 |
+
stack.enter_context(preserve_rng_state())
|
| 537 |
+
stack.enter_context(fake_mode)
|
| 538 |
+
stack.enter_context(python_dispatcher_mode)
|
| 539 |
+
stack.enter_context(PhiloxStateTracker())
|
| 540 |
+
stack.enter_context(
|
| 541 |
+
torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing()
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
from torch._library.fake_class_registry import FakeScriptObject, maybe_to_fake_obj
|
| 545 |
+
from torch._library.opaque_object import is_opaque_type
|
| 546 |
+
|
| 547 |
+
# Tracing may mutate the states the fake script object,
|
| 548 |
+
# so we need to duplicate the fake script objects so that subsequent tracing
|
| 549 |
+
# won't be affected.
|
| 550 |
+
def _dup_fake_script_obj(fake_flat_args: FakifiedFlatArgs) -> list[Any]:
|
| 551 |
+
return [
|
| 552 |
+
maybe_to_fake_obj(detect_fake_mode(fake_flat_args), arg.real_obj)
|
| 553 |
+
if isinstance(arg, FakeScriptObject) or is_opaque_type(type(arg))
|
| 554 |
+
else arg
|
| 555 |
+
for arg in fake_flat_args
|
| 556 |
+
]
|
| 557 |
+
|
| 558 |
+
needs_autograd = any(
|
| 559 |
+
x.requires_grad for x in fake_flat_args if isinstance(x, Tensor)
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
with enable_python_dispatcher():
|
| 563 |
+
# Patch set_rng_state as set_rng_state with fake tensors is
|
| 564 |
+
# nonsensical. This does not affect the collection of metadata.
|
| 565 |
+
with patch("torch.cuda.set_rng_state", lambda *args: None):
|
| 566 |
+
mod = root_module_when_exporting_non_strict(flat_fn)
|
| 567 |
+
if mod is not None:
|
| 568 |
+
ctx = _detect_attribute_assignment(mod)
|
| 569 |
+
else:
|
| 570 |
+
ctx = nullcontext()
|
| 571 |
+
|
| 572 |
+
if torch._functorch.config.fake_tensor_propagate_real_tensors:
|
| 573 |
+
# Running dynamo_timed causes fake tensor issues when
|
| 574 |
+
# propagate real tensor is switched on.
|
| 575 |
+
dynamo_timed_ctx = nullcontext()
|
| 576 |
+
else:
|
| 577 |
+
dynamo_timed_ctx = dynamo_timed(
|
| 578 |
+
"aot_collect_metadata", log_pt2_compile_event=True
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
with dynamo_timed_ctx, ctx:
|
| 582 |
+
fw_metadata = run_functionalized_fw_and_collect_metadata(
|
| 583 |
+
flat_fn,
|
| 584 |
+
flat_args_descs=flat_args_descs,
|
| 585 |
+
static_input_indices=aot_config.static_input_indices,
|
| 586 |
+
keep_input_mutations=aot_config.keep_inference_input_mutations,
|
| 587 |
+
pre_dispatch=aot_config.pre_dispatch,
|
| 588 |
+
)(*_dup_fake_script_obj(fake_flat_args))
|
| 589 |
+
|
| 590 |
+
req_subclass_dispatch = requires_subclass_dispatch(
|
| 591 |
+
fake_flat_args, fw_metadata
|
| 592 |
+
)
|
| 593 |
+
CompileEventLogger.try_add_pt2_compile(
|
| 594 |
+
"backend_compile", requires_subclass_dispatch=req_subclass_dispatch
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
output_and_mutation_safe = not any(
|
| 598 |
+
x.requires_grad
|
| 599 |
+
# view-type operations preserve requires_grad even in no_grad.
|
| 600 |
+
# Do not count aliases of inputs with requires_grad as reason to make a training graph,
|
| 601 |
+
# as AOTAutograd will perform view-replay to regenerate the view outputs at runtime,
|
| 602 |
+
# setting their grad_fn properly.
|
| 603 |
+
and not (
|
| 604 |
+
x.output_type in (OutputType.alias_of_input, OutputType.is_input)
|
| 605 |
+
and x.base_idx is not None
|
| 606 |
+
and fw_metadata.input_info[x.base_idx].requires_grad
|
| 607 |
+
)
|
| 608 |
+
for x in fw_metadata.output_info
|
| 609 |
+
) and not any(
|
| 610 |
+
x.requires_grad
|
| 611 |
+
and x.mutates_data
|
| 612 |
+
and not x.mutations_under_no_grad_or_inference_mode
|
| 613 |
+
and not x.mutations_hidden_from_autograd
|
| 614 |
+
for x in fw_metadata.input_info
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
if needs_autograd and output_and_mutation_safe:
|
| 618 |
+
# We realized that none of the outputs require grad,
|
| 619 |
+
# and none of the inputs that require grad are mutated.
|
| 620 |
+
# so we actually have an inference graph.
|
| 621 |
+
needs_autograd = False
|
| 622 |
+
|
| 623 |
+
if fw_metadata.num_intermediate_bases > 0:
|
| 624 |
+
if req_subclass_dispatch:
|
| 625 |
+
raise AssertionError(f"""\
|
| 626 |
+
torch.compile is currently being used with tensor subclass inputs.
|
| 627 |
+
We are attempting to a compile a graph with two graph outputs
|
| 628 |
+
that alias one another, specifically output indices:
|
| 629 |
+
|
| 630 |
+
{[i for i, x in enumerate(fw_metadata.output_info) if x.output_type == OutputType.alias_of_intermediate]}
|
| 631 |
+
|
| 632 |
+
ANY output aliasing (even for regular tensors) is currently unsupported if
|
| 633 |
+
there are any subclass outputs. If you run into this, please file a github
|
| 634 |
+
issue""")
|
| 635 |
+
|
| 636 |
+
if aot_config.is_export:
|
| 637 |
+
# aot_export: ban input metadata mutations for now to keep shared code paths simpler.
|
| 638 |
+
# Keeping .resize_() in the graph will require some work
|
| 639 |
+
# Allowing it but keeping the graph functional will require some calling convention changes.
|
| 640 |
+
if len([x for x in fw_metadata.input_info if x.mutates_metadata]) != 0:
|
| 641 |
+
raise RuntimeError(
|
| 642 |
+
f"""\
|
| 643 |
+
Found an input that received a metadata mutation, through e.g. a call to `.resize_()` or `.transpose_()`.
|
| 644 |
+
This is currently banned in the aot_export workflow. If you need this functionality, please file a github issue.
|
| 645 |
+
|
| 646 |
+
fw_metadata={str(fw_metadata)}"""
|
| 647 |
+
)
|
| 648 |
+
# In export, banning data mutations on inputs that require grad for now.
|
| 649 |
+
# This should be rare, and is tricky to get right. When we trace the backward,
|
| 650 |
+
# we currently trace with autograd.grad instead of .backward(), which makes it difficult
|
| 651 |
+
# to ensure that we run autograd all the way through the input **before** it saw the mutation.
|
| 652 |
+
if (
|
| 653 |
+
len(
|
| 654 |
+
[
|
| 655 |
+
x
|
| 656 |
+
for x in fw_metadata.input_info
|
| 657 |
+
if x.requires_grad and x.mutates_data
|
| 658 |
+
]
|
| 659 |
+
)
|
| 660 |
+
!= 0
|
| 661 |
+
and aot_config.export_trace_joint
|
| 662 |
+
):
|
| 663 |
+
raise RuntimeError(
|
| 664 |
+
f"""\
|
| 665 |
+
Found a graph input that requires gradients, and received a mutation.
|
| 666 |
+
This is currently banned in the aot_export workflow. If you need this functionality, please file a github issue.
|
| 667 |
+
|
| 668 |
+
fw_metadata={str(fw_metadata)}"""
|
| 669 |
+
)
|
| 670 |
+
if req_subclass_dispatch:
|
| 671 |
+
raise RuntimeError(
|
| 672 |
+
"""\
|
| 673 |
+
aot_export is not currently supported with traceable tensor subclass.
|
| 674 |
+
If you need this feature, please comment on <CREATE_ISSUE_LINK>"""
|
| 675 |
+
)
|
| 676 |
+
|
| 677 |
+
# Need to decide on a strategy for functionalized RNG: toggling via global config seems bad,
|
| 678 |
+
# and turning it on will require a non-trivial calling convention change for any export runtime.
|
| 679 |
+
if config.functionalize_rng_ops:
|
| 680 |
+
raise RuntimeError(
|
| 681 |
+
"""\
|
| 682 |
+
Functionalized RNG is not currently supported in the aot_export workflow. Please file a github issue,
|
| 683 |
+
or otherwise set torch._functorch.config.functionalize_rng_ops = False."""
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
return AOTState(
|
| 687 |
+
needs_autograd=needs_autograd,
|
| 688 |
+
flat_args=_dup_fake_script_obj(fake_flat_args),
|
| 689 |
+
flat_args_descs=flat_args_descs,
|
| 690 |
+
fw_metadata=fw_metadata,
|
| 691 |
+
# Packaging this just for later use
|
| 692 |
+
aot_config=aot_config,
|
| 693 |
+
stack=stack,
|
| 694 |
+
fake_mode=fake_mode,
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
def aot_function(
|
| 699 |
+
fn: Callable[_P, _R],
|
| 700 |
+
fw_compiler: AOTDispatchCompiler,
|
| 701 |
+
bw_compiler: AOTDispatchCompiler | None = None,
|
| 702 |
+
partition_fn: Callable[..., Any] = default_partition,
|
| 703 |
+
decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
|
| 704 |
+
num_params_buffers: int = 0,
|
| 705 |
+
keep_inference_input_mutations: bool = False,
|
| 706 |
+
inference_compiler: AOTDispatchCompiler | None = None,
|
| 707 |
+
*,
|
| 708 |
+
# Whether or not to trace with dynamic shapes
|
| 709 |
+
dynamic: bool = False,
|
| 710 |
+
enable_log: bool = True,
|
| 711 |
+
disable_functionalization: bool = False,
|
| 712 |
+
_disable_torch_fn_metadata_mode: bool = False,
|
| 713 |
+
) -> Callable[_P, Any]:
|
| 714 |
+
"""
|
| 715 |
+
Traces the forward and backward graph of :attr:`fn` using torch dispatch
|
| 716 |
+
mechanism, and then compiles the generated forward and backward graphs
|
| 717 |
+
through :attr:`fw_compiler` and :attr:`bw_compiler`.
|
| 718 |
+
|
| 719 |
+
:func:`aot_function` traces the forward and backward graph ahead of time,
|
| 720 |
+
and generates a joint forward and backward graph. :attr:`partition_fn` is
|
| 721 |
+
then used to separate out forward and backward graphs. The partitioner
|
| 722 |
+
function can be used to perform optimizations such as recomputation. One can
|
| 723 |
+
set `decompositions` dictionary to decompose the operators into a sequence
|
| 724 |
+
of core or simpler operators supported by the backend compilers.
|
| 725 |
+
|
| 726 |
+
.. warning::
|
| 727 |
+
This API is experimental and likely to change.
|
| 728 |
+
|
| 729 |
+
Args:
|
| 730 |
+
fn (Callable): A Python function that takes one or more arguments. Must
|
| 731 |
+
return one or more Tensors.
|
| 732 |
+
fw_compiler (Callable): A Python function that accepts an Fx graph with
|
| 733 |
+
Aten ops and input args, and returns a Callable that semantically is
|
| 734 |
+
equivalent to the input Fx graph.
|
| 735 |
+
bw_compiler (Optional[Callable]): A Python function that accepts an
|
| 736 |
+
Fx graph with Aten ops and input args, and returns a Callable that
|
| 737 |
+
semantically is equivalent to the input Fx graph. Default: None
|
| 738 |
+
(when None, it defaults to the :attr:`fw_compiler`)
|
| 739 |
+
partition_fn (Callable): A Python function that takes a joint forward
|
| 740 |
+
and backward graph, and partitions it into separate forward and
|
| 741 |
+
backward graphs.
|
| 742 |
+
decompositions (Dict): A dictionary to define the decomposition of
|
| 743 |
+
larger Aten ops into simpler or core Aten ops.
|
| 744 |
+
inference_compiler (Optional[Callable]): A Python function that accepts an
|
| 745 |
+
Fx graph with Aten ops and input args, and returns a Callable that
|
| 746 |
+
semantically is equivalent to the input Fx graph. inference_compiler is invoked
|
| 747 |
+
if no autograd is needed. Default: None
|
| 748 |
+
(when None, it defaults to the :attr:`fw_compiler`)
|
| 749 |
+
Returns:
|
| 750 |
+
Returns a ``Callable`` that retains the eager behavior of the original
|
| 751 |
+
:attr:`fn`, but with forward and backward graph compiled via
|
| 752 |
+
:attr:`fw_compile` and :attr:`bw_compile`.
|
| 753 |
+
|
| 754 |
+
A simple example usage of :func:`aot_function` is as follows. This example
|
| 755 |
+
will print the forward and backward graphs of the function ``fn``
|
| 756 |
+
|
| 757 |
+
>>> fn = lambda x: x.sin().cos()
|
| 758 |
+
>>> def print_compile_fn(fx_module, args):
|
| 759 |
+
>>> print(fx_module)
|
| 760 |
+
>>> return fx_module
|
| 761 |
+
>>> aot_fn = aot_function(fn, print_compile_fn)
|
| 762 |
+
>>> x = torch.randn(4, 5, requires_grad=True)
|
| 763 |
+
>>> aot_fn(x)
|
| 764 |
+
"""
|
| 765 |
+
|
| 766 |
+
aot_config = AOTConfig(
|
| 767 |
+
fw_compiler=None,
|
| 768 |
+
bw_compiler=None,
|
| 769 |
+
inference_compiler=None,
|
| 770 |
+
partition_fn=None,
|
| 771 |
+
decompositions=decompositions,
|
| 772 |
+
num_params_buffers=num_params_buffers,
|
| 773 |
+
aot_id=next(AOT_COUNTER),
|
| 774 |
+
keep_inference_input_mutations=keep_inference_input_mutations,
|
| 775 |
+
dynamic_shapes=dynamic,
|
| 776 |
+
aot_autograd_arg_pos_to_source=None,
|
| 777 |
+
is_export=False,
|
| 778 |
+
no_tangents=False,
|
| 779 |
+
enable_log=enable_log,
|
| 780 |
+
disable_functionalization=disable_functionalization,
|
| 781 |
+
_disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode,
|
| 782 |
+
)
|
| 783 |
+
cached_res = None
|
| 784 |
+
|
| 785 |
+
@wraps(fn)
|
| 786 |
+
def returned_function(*args: _P.args, **kwargs: _P.kwargs) -> Any:
|
| 787 |
+
nonlocal cached_res
|
| 788 |
+
# Now flatten the tensor args
|
| 789 |
+
flat_args = pytree.arg_tree_leaves(*args, **kwargs)
|
| 790 |
+
|
| 791 |
+
# Compile the function and save it in the cache
|
| 792 |
+
if cached_res is None:
|
| 793 |
+
flat_fn, out_spec = create_tree_flattened_fn(fn, args, kwargs)
|
| 794 |
+
(fake_mode, shape_env) = construct_fake_mode(flat_args, aot_config)
|
| 795 |
+
fake_flat_args: FakifiedFlatArgs
|
| 796 |
+
fake_flat_args, act_input_indices = process_inputs(
|
| 797 |
+
flat_args, aot_config, fake_mode, shape_env
|
| 798 |
+
)
|
| 799 |
+
# TODO: We actually could use the pytree path to make better descs.
|
| 800 |
+
# Also, the descs here are bad if you do aot_module.
|
| 801 |
+
fake_flat_args_descs: list[AOTInput] = [
|
| 802 |
+
PlainAOTInput(i) for i in range(len(fake_flat_args))
|
| 803 |
+
]
|
| 804 |
+
with contextlib.ExitStack() as stack:
|
| 805 |
+
aot_state = create_aot_state(
|
| 806 |
+
stack,
|
| 807 |
+
flat_fn,
|
| 808 |
+
fake_flat_args,
|
| 809 |
+
fake_flat_args_descs,
|
| 810 |
+
aot_config,
|
| 811 |
+
fake_mode,
|
| 812 |
+
shape_env,
|
| 813 |
+
)
|
| 814 |
+
aot_state.fw_metadata.act_input_indices = act_input_indices
|
| 815 |
+
aot_graph_capture = aot_stage1_graph_capture(aot_state, flat_fn)
|
| 816 |
+
compiled_fn, _ = aot_stage2_compile(
|
| 817 |
+
aot_state,
|
| 818 |
+
aot_graph_capture,
|
| 819 |
+
partition_fn,
|
| 820 |
+
fw_compiler,
|
| 821 |
+
bw_compiler,
|
| 822 |
+
inference_compiler,
|
| 823 |
+
)
|
| 824 |
+
cached_res = (compiled_fn, out_spec)
|
| 825 |
+
|
| 826 |
+
cached_fn, out_spec = cached_res
|
| 827 |
+
out = cached_fn(flat_args)
|
| 828 |
+
return out_spec.unflatten(out)
|
| 829 |
+
|
| 830 |
+
return returned_function
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
def aot_module(mod: nn.Module, *args: Any, **kwargs: Any) -> nn.Module:
|
| 834 |
+
"""
|
| 835 |
+
Traces the forward and backward graph of :attr:`mod` using torch dispatch
|
| 836 |
+
tracing mechanism. It is wrapper function, that underneath uses
|
| 837 |
+
:func:`aot_function` to perform tracing and compilation.
|
| 838 |
+
|
| 839 |
+
:func:`aot_module` lifts the parameters and buffers of ``nn.Module`` as inputs
|
| 840 |
+
to a new callable which is then compiled through :func:`aot_function`.
|
| 841 |
+
|
| 842 |
+
.. warning::
|
| 843 |
+
This API is experimental and likely to change.
|
| 844 |
+
|
| 845 |
+
Args:
|
| 846 |
+
mod (Callable): A ``nn.Module`` module.
|
| 847 |
+
args : args to be passed to :func:`aot_function`
|
| 848 |
+
kwargs : kwargs to be passed to :func:`aot_function`
|
| 849 |
+
|
| 850 |
+
Returns:
|
| 851 |
+
Returns a ``nn.Module`` that retains the eager behavior of the original
|
| 852 |
+
:attr:`mod`, but with forward and backward graph compiled.
|
| 853 |
+
|
| 854 |
+
"""
|
| 855 |
+
# See Note: [Fake Modules and AOTAutograd]
|
| 856 |
+
torch._dynamo.utils.assert_no_fake_params_or_buffers(mod)
|
| 857 |
+
|
| 858 |
+
def functional_call(
|
| 859 |
+
named_params: dict[str, torch.nn.Parameter],
|
| 860 |
+
named_buffers: dict[str, torch.Tensor],
|
| 861 |
+
*args: Any,
|
| 862 |
+
**kwargs: Any,
|
| 863 |
+
) -> Any:
|
| 864 |
+
params_and_buffers = {**named_params, **named_buffers}
|
| 865 |
+
return torch.func.functional_call(mod, params_and_buffers, args, kwargs)
|
| 866 |
+
|
| 867 |
+
named_params = dict(mod.named_parameters(remove_duplicate=False))
|
| 868 |
+
named_buffers = dict(mod.named_buffers(remove_duplicate=False))
|
| 869 |
+
num_params_buffers = len(named_params) + len(named_buffers)
|
| 870 |
+
compiled_f = aot_function(
|
| 871 |
+
functional_call,
|
| 872 |
+
*args,
|
| 873 |
+
# pyrefly: ignore[bad-keyword-argument]
|
| 874 |
+
num_params_buffers=num_params_buffers,
|
| 875 |
+
**kwargs,
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
class AOTModule(nn.Module):
|
| 879 |
+
def __init__(self) -> None:
|
| 880 |
+
super().__init__()
|
| 881 |
+
self.orig_module = mod
|
| 882 |
+
|
| 883 |
+
def forward(self, *args: Any, **kwargs: Any) -> Any:
|
| 884 |
+
return compiled_f(
|
| 885 |
+
named_params,
|
| 886 |
+
named_buffers,
|
| 887 |
+
*args,
|
| 888 |
+
**kwargs,
|
| 889 |
+
)
|
| 890 |
+
|
| 891 |
+
return AOTModule()
|
| 892 |
+
|
| 893 |
+
|
| 894 |
+
def autograd_cache_key(
|
| 895 |
+
graph,
|
| 896 |
+
example_inputs,
|
| 897 |
+
ignore_shape_env: bool,
|
| 898 |
+
decompositions,
|
| 899 |
+
compiler_config_extra: CompilerConfigExtra,
|
| 900 |
+
keep_inference_input_mutations: bool = False,
|
| 901 |
+
disable_functionalization: bool = False,
|
| 902 |
+
):
|
| 903 |
+
(
|
| 904 |
+
_params_buffers_flat,
|
| 905 |
+
_params_spec,
|
| 906 |
+
_buffers_spec,
|
| 907 |
+
full_args,
|
| 908 |
+
_full_args_descs,
|
| 909 |
+
aot_config,
|
| 910 |
+
) = prepare_aot_config(
|
| 911 |
+
graph,
|
| 912 |
+
example_inputs,
|
| 913 |
+
decompositions,
|
| 914 |
+
keep_inference_input_mutations,
|
| 915 |
+
ignore_shape_env,
|
| 916 |
+
force_non_lazy_backward_lowering=config.force_non_lazy_backward_lowering,
|
| 917 |
+
disable_functionalization=disable_functionalization,
|
| 918 |
+
)
|
| 919 |
+
|
| 920 |
+
fake_mode, shape_env = construct_fake_mode(full_args, aot_config)
|
| 921 |
+
fake_flat_args, _act_input_indices = process_inputs(
|
| 922 |
+
full_args, aot_config, fake_mode, shape_env, ignore_shape_env
|
| 923 |
+
)
|
| 924 |
+
|
| 925 |
+
return autograd_cache.autograd_cache_key(
|
| 926 |
+
graph, fake_flat_args, aot_config, compiler_config_extra
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
def prepare_aot_config(
|
| 931 |
+
mod: nn.Module,
|
| 932 |
+
args: Iterable[Any],
|
| 933 |
+
decompositions: dict[OpOverload, Callable[..., Any]] | None,
|
| 934 |
+
keep_inference_input_mutations: bool,
|
| 935 |
+
ignore_shape_env: bool,
|
| 936 |
+
*,
|
| 937 |
+
force_non_lazy_backward_lowering: bool = False,
|
| 938 |
+
disable_functionalization: bool = False,
|
| 939 |
+
_disable_torch_fn_metadata_mode: bool = False,
|
| 940 |
+
) -> tuple[
|
| 941 |
+
list[torch.nn.Parameter | Tensor],
|
| 942 |
+
list[str],
|
| 943 |
+
list[str],
|
| 944 |
+
list[Any],
|
| 945 |
+
list[Any],
|
| 946 |
+
AOTConfig,
|
| 947 |
+
]:
|
| 948 |
+
# TODO: There's something a bit suspicious here; typically simplified
|
| 949 |
+
# module shouldn't actually have any parameters...
|
| 950 |
+
params = dict(mod.named_parameters(remove_duplicate=False))
|
| 951 |
+
buffers = dict(dict(mod.named_buffers(remove_duplicate=False)))
|
| 952 |
+
|
| 953 |
+
params_flat, params_spec = list(params.values()), list(params.keys())
|
| 954 |
+
params_len = len(params_flat)
|
| 955 |
+
|
| 956 |
+
buffers_flat, buffers_spec = list(buffers.values()), list(buffers.keys())
|
| 957 |
+
buffers_len = len(buffers_flat)
|
| 958 |
+
|
| 959 |
+
params_buffers = {**params, **buffers}
|
| 960 |
+
params_buffers_flat = params_flat + buffers_flat
|
| 961 |
+
|
| 962 |
+
full_args = [*params_flat, *buffers_flat, *args]
|
| 963 |
+
|
| 964 |
+
# OK, set up the descs
|
| 965 |
+
|
| 966 |
+
full_args_descs: list[DifferentiableAOTInput] = []
|
| 967 |
+
full_args_descs.extend(ParamAOTInput(fqn) for fqn in params_spec)
|
| 968 |
+
full_args_descs.extend(BufferAOTInput(fqn) for fqn in buffers_spec)
|
| 969 |
+
|
| 970 |
+
# TODO: These tracing_context fields should become unnecessary once we
|
| 971 |
+
# always maintain sources on all arguments
|
| 972 |
+
if tracing_context := torch._guards.TracingContext.try_get():
|
| 973 |
+
# NB: TracingContext misnames this, the "params" here also contains
|
| 974 |
+
# buffers
|
| 975 |
+
tracing_context.params_flat = params_buffers_flat
|
| 976 |
+
(
|
| 977 |
+
tracing_context.params_flat_unwrap_subclasses,
|
| 978 |
+
tracing_context.params_unwrapped_to_flat_index,
|
| 979 |
+
) = unwrap_tensor_subclasses_with_indices_to_original(params_buffers_flat)
|
| 980 |
+
|
| 981 |
+
# TODO: Might be nice to hold on to the Dynamo source here in full_args_descs!
|
| 982 |
+
(
|
| 983 |
+
aot_autograd_arg_pos_to_source,
|
| 984 |
+
static_input_indices,
|
| 985 |
+
) = _try_get_metadata_from_dynamo(
|
| 986 |
+
mod, params_buffers.keys(), len(full_args), full_args_descs
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
dynamic_shapes = False
|
| 990 |
+
for x in full_args:
|
| 991 |
+
if isinstance(x, FakeTensor):
|
| 992 |
+
dynamic_shapes = x.fake_mode.shape_env is not None
|
| 993 |
+
break
|
| 994 |
+
|
| 995 |
+
aot_config = AOTConfig(
|
| 996 |
+
fw_compiler=None,
|
| 997 |
+
bw_compiler=None,
|
| 998 |
+
inference_compiler=None,
|
| 999 |
+
partition_fn=None,
|
| 1000 |
+
decompositions=decompositions,
|
| 1001 |
+
num_params_buffers=params_len + buffers_len,
|
| 1002 |
+
aot_id=next(AOT_COUNTER),
|
| 1003 |
+
keep_inference_input_mutations=keep_inference_input_mutations,
|
| 1004 |
+
dynamic_shapes=dynamic_shapes,
|
| 1005 |
+
# pyrefly: ignore[bad-argument-type]
|
| 1006 |
+
aot_autograd_arg_pos_to_source=aot_autograd_arg_pos_to_source,
|
| 1007 |
+
static_input_indices=static_input_indices,
|
| 1008 |
+
is_export=False,
|
| 1009 |
+
no_tangents=False,
|
| 1010 |
+
cache_info=None,
|
| 1011 |
+
ignore_shape_env=ignore_shape_env,
|
| 1012 |
+
precompile_backend_id=getattr(mod, "_backend_id", None),
|
| 1013 |
+
force_non_lazy_backward_lowering=force_non_lazy_backward_lowering,
|
| 1014 |
+
disable_functionalization=disable_functionalization,
|
| 1015 |
+
_disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode,
|
| 1016 |
+
)
|
| 1017 |
+
|
| 1018 |
+
return (
|
| 1019 |
+
params_buffers_flat,
|
| 1020 |
+
params_spec,
|
| 1021 |
+
buffers_spec,
|
| 1022 |
+
full_args,
|
| 1023 |
+
full_args_descs,
|
| 1024 |
+
aot_config,
|
| 1025 |
+
)
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
def prepare_aot_module_simplified(
|
| 1029 |
+
mod: nn.Module,
|
| 1030 |
+
args: Iterable[Any],
|
| 1031 |
+
kwargs: dict[str, Any] | None,
|
| 1032 |
+
decompositions: dict[OpOverload, Callable[..., Any]] | None,
|
| 1033 |
+
keep_inference_input_mutations: bool,
|
| 1034 |
+
ignore_shape_env: bool,
|
| 1035 |
+
flatten: bool,
|
| 1036 |
+
*,
|
| 1037 |
+
force_non_lazy_backward_lowering: bool = False,
|
| 1038 |
+
disable_functionalization: bool = False,
|
| 1039 |
+
_record_nn_module_stack: bool = False,
|
| 1040 |
+
_disable_torch_fn_metadata_mode: bool = False,
|
| 1041 |
+
) -> tuple[
|
| 1042 |
+
Any,
|
| 1043 |
+
list[torch.nn.Parameter | Tensor],
|
| 1044 |
+
list[str],
|
| 1045 |
+
list[str],
|
| 1046 |
+
FakifiedFlatArgs,
|
| 1047 |
+
list[Any],
|
| 1048 |
+
AOTConfig,
|
| 1049 |
+
FakeTensorMode,
|
| 1050 |
+
ShapeEnv | None,
|
| 1051 |
+
pytree.TreeSpec | None,
|
| 1052 |
+
PytreeThunk | None,
|
| 1053 |
+
list[int],
|
| 1054 |
+
]:
|
| 1055 |
+
if not flatten:
|
| 1056 |
+
if kwargs is not None:
|
| 1057 |
+
raise AssertionError("kwargs must be None when flatten=False")
|
| 1058 |
+
elif kwargs is None:
|
| 1059 |
+
kwargs = {}
|
| 1060 |
+
|
| 1061 |
+
(
|
| 1062 |
+
params_buffers_flat,
|
| 1063 |
+
params_spec,
|
| 1064 |
+
buffers_spec,
|
| 1065 |
+
full_args,
|
| 1066 |
+
full_args_descs,
|
| 1067 |
+
aot_config,
|
| 1068 |
+
) = prepare_aot_config(
|
| 1069 |
+
mod,
|
| 1070 |
+
args,
|
| 1071 |
+
decompositions,
|
| 1072 |
+
keep_inference_input_mutations,
|
| 1073 |
+
ignore_shape_env,
|
| 1074 |
+
force_non_lazy_backward_lowering=force_non_lazy_backward_lowering,
|
| 1075 |
+
disable_functionalization=disable_functionalization,
|
| 1076 |
+
_disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode,
|
| 1077 |
+
)
|
| 1078 |
+
|
| 1079 |
+
params_buffers_spec = params_spec + buffers_spec
|
| 1080 |
+
|
| 1081 |
+
# NB: This doesn't change the in/out convention, except adding the
|
| 1082 |
+
# parameters as explicit arguments
|
| 1083 |
+
functional_call = create_functional_call(
|
| 1084 |
+
mod,
|
| 1085 |
+
params_buffers_spec,
|
| 1086 |
+
aot_config.num_params_buffers,
|
| 1087 |
+
strict_out_tuple=not flatten,
|
| 1088 |
+
# We need this for export to run ModuleStackTracer
|
| 1089 |
+
# instead of PythonKeyTracer
|
| 1090 |
+
store_orig_mod=_record_nn_module_stack,
|
| 1091 |
+
)
|
| 1092 |
+
|
| 1093 |
+
in_spec, out_spec = None, None
|
| 1094 |
+
if flatten:
|
| 1095 |
+
functional_call, out_spec = create_tree_flattened_fn(
|
| 1096 |
+
functional_call, full_args, kwargs
|
| 1097 |
+
)
|
| 1098 |
+
full_args, in_spec = pytree.tree_flatten((full_args, kwargs))
|
| 1099 |
+
|
| 1100 |
+
# TODO: it would be better to put pytree information in here
|
| 1101 |
+
full_args_descs.extend(
|
| 1102 |
+
PlainAOTInput(i) for i in range(len(full_args) - len(full_args_descs))
|
| 1103 |
+
)
|
| 1104 |
+
|
| 1105 |
+
fake_mode, shape_env = construct_fake_mode(full_args, aot_config)
|
| 1106 |
+
# NB: full_args_descs not needed here, fake_flat_args is 1:1 with full_args
|
| 1107 |
+
fake_flat_args, act_input_indices = process_inputs(
|
| 1108 |
+
full_args, aot_config, fake_mode, shape_env, ignore_shape_env
|
| 1109 |
+
)
|
| 1110 |
+
|
| 1111 |
+
return (
|
| 1112 |
+
functional_call,
|
| 1113 |
+
params_buffers_flat,
|
| 1114 |
+
params_spec,
|
| 1115 |
+
buffers_spec,
|
| 1116 |
+
fake_flat_args,
|
| 1117 |
+
full_args_descs,
|
| 1118 |
+
aot_config,
|
| 1119 |
+
fake_mode,
|
| 1120 |
+
shape_env,
|
| 1121 |
+
in_spec,
|
| 1122 |
+
out_spec,
|
| 1123 |
+
act_input_indices,
|
| 1124 |
+
)
|
| 1125 |
+
|
| 1126 |
+
|
| 1127 |
+
def aot_module_simplified(
|
| 1128 |
+
mod: torch.fx.GraphModule | torch._dynamo.utils.GmWrapper,
|
| 1129 |
+
args: Sequence[Any],
|
| 1130 |
+
fw_compiler: AOTDispatchCompiler,
|
| 1131 |
+
bw_compiler: AOTDispatchCompiler | None = None,
|
| 1132 |
+
partition_fn: Callable[..., Any] = default_partition,
|
| 1133 |
+
decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
|
| 1134 |
+
keep_inference_input_mutations: bool = False,
|
| 1135 |
+
inference_compiler: AOTDispatchCompiler | None = None,
|
| 1136 |
+
# TODO: This doesn't seem to be used in any nontrivial way, check if it's
|
| 1137 |
+
# actually needed
|
| 1138 |
+
compiler_config_extra: CompilerConfigExtra | None = None,
|
| 1139 |
+
ignore_shape_env: bool = False,
|
| 1140 |
+
disable_functionalization: bool = False,
|
| 1141 |
+
# Optional callback to run passes on the module at the start of AOT autograd.
|
| 1142 |
+
pre_grad_passes: Callable[
|
| 1143 |
+
[torch.fx.GraphModule, Sequence[InputType]], torch.fx.GraphModule
|
| 1144 |
+
]
|
| 1145 |
+
| None = None,
|
| 1146 |
+
compile_region_name: str | None = None,
|
| 1147 |
+
) -> Callable[..., Any]:
|
| 1148 |
+
"""
|
| 1149 |
+
This is the simplified or low overhead version of aot_module. For frontends
|
| 1150 |
+
like TorchDynamo, the input functions/modules to AOT are static and have
|
| 1151 |
+
unpacked inputs/outputs. This gives us an opportunity to remove the
|
| 1152 |
+
(1) pytree overhead to parse inputs/outputs,
|
| 1153 |
+
(2) AOT Autograd cache,
|
| 1154 |
+
(3) Reading of params/buffers in every forward call
|
| 1155 |
+
|
| 1156 |
+
:func:`aot_module_simplified` removes these overheads.
|
| 1157 |
+
"""
|
| 1158 |
+
|
| 1159 |
+
pre_grad_pass_timing: Literal["early", "late"] = resolve_pre_grad_pass_timing()
|
| 1160 |
+
|
| 1161 |
+
if (
|
| 1162 |
+
pre_grad_pass_timing == "early"
|
| 1163 |
+
and pre_grad_passes
|
| 1164 |
+
and isinstance(mod, torch.fx.GraphModule)
|
| 1165 |
+
):
|
| 1166 |
+
mod = pre_grad_passes(mod, args)
|
| 1167 |
+
|
| 1168 |
+
with contextlib.ExitStack() as stack:
|
| 1169 |
+
(
|
| 1170 |
+
functional_call,
|
| 1171 |
+
params_buffers_flat,
|
| 1172 |
+
_params_spec,
|
| 1173 |
+
_buffers_spec,
|
| 1174 |
+
fake_flat_args,
|
| 1175 |
+
full_args_descs,
|
| 1176 |
+
aot_config,
|
| 1177 |
+
fake_mode,
|
| 1178 |
+
shape_env,
|
| 1179 |
+
_in_spec,
|
| 1180 |
+
_out_spec,
|
| 1181 |
+
act_input_indices,
|
| 1182 |
+
) = prepare_aot_module_simplified(
|
| 1183 |
+
mod,
|
| 1184 |
+
args,
|
| 1185 |
+
None,
|
| 1186 |
+
decompositions,
|
| 1187 |
+
keep_inference_input_mutations,
|
| 1188 |
+
ignore_shape_env,
|
| 1189 |
+
flatten=False,
|
| 1190 |
+
force_non_lazy_backward_lowering=config.force_non_lazy_backward_lowering,
|
| 1191 |
+
disable_functionalization=disable_functionalization,
|
| 1192 |
+
)
|
| 1193 |
+
|
| 1194 |
+
compiled_fn = None
|
| 1195 |
+
|
| 1196 |
+
if (
|
| 1197 |
+
isinstance(fw_compiler, SerializableAOTDispatchCompiler)
|
| 1198 |
+
or torch._functorch.config.force_autograd_cache
|
| 1199 |
+
):
|
| 1200 |
+
local = should_use_local_autograd_cache()
|
| 1201 |
+
remote = should_use_remote_autograd_cache()
|
| 1202 |
+
if local or remote:
|
| 1203 |
+
set_feature_use("aot_autograd_remote_cache", remote)
|
| 1204 |
+
compiled_fn = AOTAutogradCache.try_load(
|
| 1205 |
+
mod,
|
| 1206 |
+
fake_flat_args,
|
| 1207 |
+
aot_config,
|
| 1208 |
+
compiler_config_extra,
|
| 1209 |
+
local,
|
| 1210 |
+
remote,
|
| 1211 |
+
compile_region_name=compile_region_name,
|
| 1212 |
+
)
|
| 1213 |
+
|
| 1214 |
+
if compiled_fn is None:
|
| 1215 |
+
if (
|
| 1216 |
+
pre_grad_pass_timing == "late"
|
| 1217 |
+
and pre_grad_passes
|
| 1218 |
+
and isinstance(mod, torch.fx.GraphModule)
|
| 1219 |
+
):
|
| 1220 |
+
mod = pre_grad_passes(mod, args)
|
| 1221 |
+
|
| 1222 |
+
stack.enter_context(compiled_autograd._disable())
|
| 1223 |
+
aot_state = create_aot_state(
|
| 1224 |
+
stack,
|
| 1225 |
+
functional_call,
|
| 1226 |
+
fake_flat_args,
|
| 1227 |
+
full_args_descs,
|
| 1228 |
+
aot_config,
|
| 1229 |
+
fake_mode,
|
| 1230 |
+
shape_env,
|
| 1231 |
+
)
|
| 1232 |
+
aot_state.fw_metadata.act_input_indices = act_input_indices
|
| 1233 |
+
aot_graph_capture = aot_stage1_graph_capture(aot_state, functional_call)
|
| 1234 |
+
compiled_fn, _ = aot_stage2_compile(
|
| 1235 |
+
aot_state,
|
| 1236 |
+
aot_graph_capture,
|
| 1237 |
+
partition_fn,
|
| 1238 |
+
fw_compiler,
|
| 1239 |
+
bw_compiler,
|
| 1240 |
+
inference_compiler,
|
| 1241 |
+
)
|
| 1242 |
+
if compiled_fn is None:
|
| 1243 |
+
raise AssertionError("compiled_fn must not be None")
|
| 1244 |
+
if isinstance(mod, torch._dynamo.utils.GmWrapper):
|
| 1245 |
+
# This function is called by the flatten_graph_inputs wrapper, which boxes
|
| 1246 |
+
# the inputs so that they can be freed before the end of this scope.
|
| 1247 |
+
# For overhead reasons, this is not the default wrapper, see comment:
|
| 1248 |
+
# https://github.com/pytorch/pytorch/pull/122535/files#r1560096481
|
| 1249 |
+
@simple_wraps(compiled_fn)
|
| 1250 |
+
def forward(runtime_args: list[Any]) -> Any:
|
| 1251 |
+
flat_args = []
|
| 1252 |
+
flat_args.extend(params_buffers_flat)
|
| 1253 |
+
flat_args.extend(runtime_args)
|
| 1254 |
+
runtime_args.clear()
|
| 1255 |
+
if compiled_fn is None:
|
| 1256 |
+
raise AssertionError("compiled_fn must not be None")
|
| 1257 |
+
return compiled_fn(flat_args)
|
| 1258 |
+
|
| 1259 |
+
else:
|
| 1260 |
+
# TODO: There is something deeply wrong here; compiled_fn running with
|
| 1261 |
+
# the boxed calling convention, but aot_module_simplified somehow
|
| 1262 |
+
# historically returned a function that was not the boxed calling
|
| 1263 |
+
# convention. This should get fixed...
|
| 1264 |
+
# NB: GraphModule/nn.Module rely on the non-boxed calling convention here
|
| 1265 |
+
@simple_wraps(compiled_fn)
|
| 1266 |
+
def forward(*runtime_args: tuple[Any]) -> Any:
|
| 1267 |
+
full_args = []
|
| 1268 |
+
full_args.extend(params_buffers_flat)
|
| 1269 |
+
# pyrefly: ignore[bad-argument-type]
|
| 1270 |
+
full_args.extend(runtime_args)
|
| 1271 |
+
if compiled_fn is None:
|
| 1272 |
+
raise AssertionError("compiled_fn must not be None")
|
| 1273 |
+
return compiled_fn(full_args)
|
| 1274 |
+
|
| 1275 |
+
# Just for convenience
|
| 1276 |
+
forward.zero_grad = mod.zero_grad # type: ignore[attr-defined]
|
| 1277 |
+
forward.named_parameters = mod.named_parameters # type: ignore[attr-defined]
|
| 1278 |
+
forward.named_buffers = mod.named_buffers # type: ignore[attr-defined]
|
| 1279 |
+
|
| 1280 |
+
# Add a serialize function
|
| 1281 |
+
def grab_serialize_fn(fn: Any) -> Callable[..., Any] | None:
|
| 1282 |
+
if isinstance(fn, SerializableCompiledFunction):
|
| 1283 |
+
return fn.serialize_fn
|
| 1284 |
+
elif hasattr(fn, "__wrapped__"):
|
| 1285 |
+
return grab_serialize_fn(fn.__wrapped__)
|
| 1286 |
+
else:
|
| 1287 |
+
return None
|
| 1288 |
+
|
| 1289 |
+
forward.serialize = grab_serialize_fn(forward) # type: ignore[attr-defined]
|
| 1290 |
+
return forward
|
| 1291 |
+
|
| 1292 |
+
|
| 1293 |
+
def boxed_nop_preserve_node_meta(
|
| 1294 |
+
gm: torch.fx.GraphModule, example_inputs: Sequence[InputType]
|
| 1295 |
+
) -> Any:
|
| 1296 |
+
def run(args: list[Any]) -> OutputCode:
|
| 1297 |
+
with torch.fx.traceback.preserve_node_meta():
|
| 1298 |
+
return torch.fx.Interpreter(gm).boxed_run(args)
|
| 1299 |
+
|
| 1300 |
+
run._boxed_call = True # type: ignore[attr-defined]
|
| 1301 |
+
return run
|
| 1302 |
+
|
| 1303 |
+
|
| 1304 |
+
def aot_export_joint_with_descriptors(
|
| 1305 |
+
stack: contextlib.ExitStack,
|
| 1306 |
+
mod: nn.Module,
|
| 1307 |
+
args: tuple[Any, ...],
|
| 1308 |
+
kwargs: dict[str, Any] | None = None,
|
| 1309 |
+
*,
|
| 1310 |
+
decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
|
| 1311 |
+
keep_inference_input_mutations: bool = False,
|
| 1312 |
+
ignore_shape_env: bool = False,
|
| 1313 |
+
disable_functionalization: bool = False,
|
| 1314 |
+
_record_nn_module_stack: bool = False,
|
| 1315 |
+
_disable_torch_fn_metadata_mode: bool = False,
|
| 1316 |
+
) -> JointWithDescriptors:
|
| 1317 |
+
"""
|
| 1318 |
+
This API captures the joint graph for an nn.Module. However, unlike
|
| 1319 |
+
aot_export_joint_simple or aot_export_module(trace_joint=True), the
|
| 1320 |
+
calling convention of the produced joint graph follows no fixed positional
|
| 1321 |
+
schema; for example, you cannot rely on the second argument of the traced
|
| 1322 |
+
joint graph to correspond to the second argument of the module you traced.
|
| 1323 |
+
However, the inputs and outputs of the traced graph are schematized
|
| 1324 |
+
with **descriptors**, annotated on meta['desc'] on the placeholder and
|
| 1325 |
+
return FX nodes, which you can use to determine the meaning of arguments.
|
| 1326 |
+
|
| 1327 |
+
The major benefit of using this export rather than aot_export_joint_simple
|
| 1328 |
+
is that we have feature parity with all situations that torch.compile
|
| 1329 |
+
supports (via aot_module_simplified), including handling for more
|
| 1330 |
+
complicated cases such as multiple differentiable outputs, input mutations
|
| 1331 |
+
that must be handled outside of the graph, tensor subclasses, etc.
|
| 1332 |
+
|
| 1333 |
+
What can you do with one of these joint graphs with descriptors? The
|
| 1334 |
+
motivating use case (autoparallel) involves taking the joint graph, doing
|
| 1335 |
+
optimizations on it, and then turning it back into a callable so it can be
|
| 1336 |
+
torch.compile'd at a later point in time. This cannot be done as a
|
| 1337 |
+
traditional torch.compile joint graph pass for two reasons:
|
| 1338 |
+
|
| 1339 |
+
1. The sharding of parameters must be decided before parameter
|
| 1340 |
+
initialization / checkpoint load, far before torch.compile would
|
| 1341 |
+
ordinarily run.
|
| 1342 |
+
|
| 1343 |
+
2. We need to change the meaning of parameters (e.g., we might replace
|
| 1344 |
+
a replicated parameter with a sharded version of it, changing its
|
| 1345 |
+
input size). torch.compile is ordinarily semantics preserving, and
|
| 1346 |
+
not allowed to change the meaning of inputs.
|
| 1347 |
+
|
| 1348 |
+
Some descriptors can be quite exotic, so we recommend thinking carefully
|
| 1349 |
+
if there is a safe fallback you can apply to descriptors you don't understand.
|
| 1350 |
+
For example, you should have some way to handle not finding a particular
|
| 1351 |
+
input exactly as is in the final FX graph inputs.
|
| 1352 |
+
|
| 1353 |
+
Note: When using this API, you must create and enter an ExitStack context
|
| 1354 |
+
manager, which will be passed into this function. This context manager
|
| 1355 |
+
must remain active if you call the compile function to finish compilation.
|
| 1356 |
+
(TODO: We may relax this requirement by having AOTAutograd keep track of
|
| 1357 |
+
how to reconstruct all the context managers at a later point in time.)
|
| 1358 |
+
|
| 1359 |
+
NB: You're not obligated to do a /full/ compile in stage2; instead you can
|
| 1360 |
+
leave the forward/backward compilers unspecified in which case the
|
| 1361 |
+
partitioned FX graphs will directly run. The overall autograd Function
|
| 1362 |
+
can be allowed in graph so you can reprocess it in the context of a
|
| 1363 |
+
(potentially larger) compiled region later.
|
| 1364 |
+
|
| 1365 |
+
NB: These APIs do NOT hit cache, as we only ever cache the final compile results,
|
| 1366 |
+
not the intermediate export result.
|
| 1367 |
+
|
| 1368 |
+
NB: If the passed nn.Module has parameters and buffers on it, we will
|
| 1369 |
+
generate extra implicit parameter/buffer arguments and assign ParamAOTInput
|
| 1370 |
+
and BufferAOTInput descriptors to them. However, if you generate the input
|
| 1371 |
+
nn.Module from a mechanism like Dynamo, you will NOT get these descriptors
|
| 1372 |
+
(because Dynamo will already have taken care of lifting the parameters/buffers
|
| 1373 |
+
into arguments!) In that case, it would be necessary to analyze the Sources
|
| 1374 |
+
of the inputs to determine if inputs are parameters and their FQNs.
|
| 1375 |
+
"""
|
| 1376 |
+
|
| 1377 |
+
(
|
| 1378 |
+
functional_call,
|
| 1379 |
+
_params_buffers_flat,
|
| 1380 |
+
params_spec,
|
| 1381 |
+
buffers_spec,
|
| 1382 |
+
fake_flat_args,
|
| 1383 |
+
full_args_descs,
|
| 1384 |
+
aot_config,
|
| 1385 |
+
fake_mode,
|
| 1386 |
+
shape_env,
|
| 1387 |
+
in_spec,
|
| 1388 |
+
out_spec,
|
| 1389 |
+
act_input_indices,
|
| 1390 |
+
) = prepare_aot_module_simplified(
|
| 1391 |
+
mod,
|
| 1392 |
+
args,
|
| 1393 |
+
kwargs,
|
| 1394 |
+
# In contrast, decompositions are needed at this stage.
|
| 1395 |
+
decompositions,
|
| 1396 |
+
keep_inference_input_mutations,
|
| 1397 |
+
ignore_shape_env,
|
| 1398 |
+
flatten=True,
|
| 1399 |
+
# Without this, we will attempt to "compile" the backward lazily
|
| 1400 |
+
# at runtime, but this is pointless because it's just boxed_nop,
|
| 1401 |
+
# it's trivial. But this will get Inductor confused about scoping
|
| 1402 |
+
# Metric(s) {'is_forward'} have already been set in the current
|
| 1403 |
+
# context.
|
| 1404 |
+
force_non_lazy_backward_lowering=True,
|
| 1405 |
+
disable_functionalization=disable_functionalization,
|
| 1406 |
+
_record_nn_module_stack=_record_nn_module_stack,
|
| 1407 |
+
_disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode,
|
| 1408 |
+
)
|
| 1409 |
+
|
| 1410 |
+
# TODO: Maybe this should be in create_aot_state? Not sure, that would
|
| 1411 |
+
# increase its scope
|
| 1412 |
+
stack.enter_context(compiled_autograd._disable())
|
| 1413 |
+
|
| 1414 |
+
aot_state = create_aot_state(
|
| 1415 |
+
stack,
|
| 1416 |
+
functional_call,
|
| 1417 |
+
fake_flat_args,
|
| 1418 |
+
full_args_descs,
|
| 1419 |
+
aot_config,
|
| 1420 |
+
fake_mode,
|
| 1421 |
+
shape_env,
|
| 1422 |
+
)
|
| 1423 |
+
aot_state.fw_metadata.act_input_indices = act_input_indices
|
| 1424 |
+
|
| 1425 |
+
# NB: no cache lookup!
|
| 1426 |
+
aot_graph_capture = aot_stage1_graph_capture(aot_state, functional_call)
|
| 1427 |
+
|
| 1428 |
+
if out_spec is None or out_spec.spec is None:
|
| 1429 |
+
raise AssertionError("out_spec and out_spec.spec must not be None")
|
| 1430 |
+
if in_spec is None:
|
| 1431 |
+
raise AssertionError("in_spec must not be None")
|
| 1432 |
+
return JointWithDescriptors(
|
| 1433 |
+
_aot_state=aot_state,
|
| 1434 |
+
_aot_graph_capture=aot_graph_capture,
|
| 1435 |
+
params_spec=params_spec,
|
| 1436 |
+
buffers_spec=buffers_spec,
|
| 1437 |
+
in_spec=in_spec,
|
| 1438 |
+
out_spec=out_spec.spec,
|
| 1439 |
+
)
|
| 1440 |
+
|
| 1441 |
+
|
| 1442 |
+
def aot_compile_joint_with_descriptors(
|
| 1443 |
+
jd: JointWithDescriptors,
|
| 1444 |
+
*,
|
| 1445 |
+
partition_fn: Callable[..., Any] = default_partition,
|
| 1446 |
+
fw_compiler: AOTDispatchCompiler = boxed_nop_preserve_node_meta,
|
| 1447 |
+
bw_compiler: AOTDispatchCompiler | None = boxed_nop_preserve_node_meta,
|
| 1448 |
+
serializable: bool = False,
|
| 1449 |
+
) -> Callable[..., Any]:
|
| 1450 |
+
"""
|
| 1451 |
+
Companion function for aot_export_joint_with_descriptors which compiles the joint
|
| 1452 |
+
graph into a callable function that follows a standard calling convention.
|
| 1453 |
+
params_flat all are arguments.
|
| 1454 |
+
|
| 1455 |
+
Note: We do NOT instantiate the module; this gives you the flexibility to subclass it and
|
| 1456 |
+
customize its behavior without having to worry about FQN rebinding.
|
| 1457 |
+
|
| 1458 |
+
Args:
|
| 1459 |
+
serializable: If True, configures the compilation to produce a serializable
|
| 1460 |
+
callable by leveraging AOTAutogradCache machinery. This sets up the
|
| 1461 |
+
necessary cache_info and patches config options required for serialization.
|
| 1462 |
+
When True, this function will always return a BundledAOTAutogradSerializableCallable.
|
| 1463 |
+
"""
|
| 1464 |
+
# TODO: Consider if we should allow_in_graph the result by default.
|
| 1465 |
+
from torch._dynamo.aot_compile_types import (
|
| 1466 |
+
BundledAOTAutogradSerializableCallable,
|
| 1467 |
+
SerializableCallable,
|
| 1468 |
+
)
|
| 1469 |
+
from torch._functorch._aot_autograd.schemas import AOTAutogradCacheInfo
|
| 1470 |
+
from torch._guards import detect_fake_mode
|
| 1471 |
+
from torch._inductor.output_code import OutputCode
|
| 1472 |
+
|
| 1473 |
+
fw_compiler = SerializableAOTDispatchCompiler(OutputCode, fw_compiler)
|
| 1474 |
+
|
| 1475 |
+
cache_ctx = nullcontext()
|
| 1476 |
+
if serializable:
|
| 1477 |
+
jd._aot_state.aot_config.cache_info = AOTAutogradCacheInfo(
|
| 1478 |
+
jd.cache_hash(),
|
| 1479 |
+
time.time_ns(),
|
| 1480 |
+
forward_symints=[],
|
| 1481 |
+
)
|
| 1482 |
+
cache_ctx = torch._functorch.config.patch(
|
| 1483 |
+
{
|
| 1484 |
+
"strict_autograd_cache": True,
|
| 1485 |
+
"bundled_autograd_cache": True,
|
| 1486 |
+
"force_non_lazy_backward_lowering": True,
|
| 1487 |
+
"bypass_autograd_cache_key": True,
|
| 1488 |
+
}
|
| 1489 |
+
)
|
| 1490 |
+
|
| 1491 |
+
# Set up a TracingContext if one isn't already available.
|
| 1492 |
+
# This is needed for compilers (like regional_inductor) that call
|
| 1493 |
+
# standalone_compile with dynamic_shapes="from_tracing_context".
|
| 1494 |
+
tracing_context = torch._guards.TracingContext.try_get()
|
| 1495 |
+
if tracing_context is None:
|
| 1496 |
+
fake_mode = detect_fake_mode(jd._aot_state.flat_args)
|
| 1497 |
+
if fake_mode is not None:
|
| 1498 |
+
tracing_context = torch._guards.TracingContext(fake_mode)
|
| 1499 |
+
tracing_ctx = torch._guards.tracing(tracing_context)
|
| 1500 |
+
else:
|
| 1501 |
+
tracing_ctx = nullcontext()
|
| 1502 |
+
else:
|
| 1503 |
+
tracing_ctx = nullcontext()
|
| 1504 |
+
|
| 1505 |
+
with cache_ctx, tracing_ctx:
|
| 1506 |
+
compiled_fn, _ = aot_stage2_compile(
|
| 1507 |
+
jd._aot_state,
|
| 1508 |
+
jd._aot_graph_capture,
|
| 1509 |
+
partition_fn,
|
| 1510 |
+
fw_compiler,
|
| 1511 |
+
bw_compiler,
|
| 1512 |
+
)
|
| 1513 |
+
|
| 1514 |
+
if not isinstance(compiled_fn, SerializableCallable) and hasattr(
|
| 1515 |
+
compiled_fn, "serialize"
|
| 1516 |
+
):
|
| 1517 |
+
compiled_fn = BundledAOTAutogradSerializableCallable(compiled_fn)
|
| 1518 |
+
|
| 1519 |
+
# Cribbed from torch/export/pt2_archive/_package.py
|
| 1520 |
+
@simple_wraps(compiled_fn)
|
| 1521 |
+
@torch._dynamo.nonstrict_trace # allow recursive compilation
|
| 1522 |
+
def unflattened_compiled_fn(*args: Any, **kwargs: Any) -> Any:
|
| 1523 |
+
flat_inputs = pytree.tree_flatten((args, reorder_kwargs(kwargs, jd.in_spec)))[0]
|
| 1524 |
+
# TODO: do I need to filter? I hope not!
|
| 1525 |
+
flat_outputs = compiled_fn(flat_inputs)
|
| 1526 |
+
return pytree.tree_unflatten(flat_outputs, jd.out_spec)
|
| 1527 |
+
|
| 1528 |
+
return unflattened_compiled_fn
|
| 1529 |
+
|
| 1530 |
+
|
| 1531 |
+
def aot_export_module(
|
| 1532 |
+
mod: nn.Module,
|
| 1533 |
+
args: Iterable[Any],
|
| 1534 |
+
*,
|
| 1535 |
+
decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
|
| 1536 |
+
# If true, we'll return a joint forward-backward graph,
|
| 1537 |
+
# As well as metadata on the loss + gradients in the backward.
|
| 1538 |
+
trace_joint: bool,
|
| 1539 |
+
# If trace_joint is True, we expect your module to return a scalar loss.
|
| 1540 |
+
# Your module can return multiple outputs, so you must specify which output the loss is.
|
| 1541 |
+
output_loss_index: int | None = None,
|
| 1542 |
+
pre_dispatch: bool = False,
|
| 1543 |
+
# If None, will be inferred from inputs and mod.graph.nodes if mod is a graph module, but the inferred result might be wrong.
|
| 1544 |
+
dynamic_shapes: bool | None = None,
|
| 1545 |
+
kwargs: dict[str, Any] | None = None,
|
| 1546 |
+
) -> tuple[Callable[..., Any] | torch.fx.GraphModule, GraphSignature]:
|
| 1547 |
+
"""
|
| 1548 |
+
This function takes in a module, and returns:
|
| 1549 |
+
(1) an FX graph that can be exported
|
| 1550 |
+
(2) some metadata about the graph
|
| 1551 |
+
|
| 1552 |
+
If `trace_joint=True` we will return a joint graph of the forward + backward.
|
| 1553 |
+
|
| 1554 |
+
The traced FX graph will have the following properties compared to the original module:
|
| 1555 |
+
(1) Inputs and outputs to the module will be pytree-flattened
|
| 1556 |
+
(2) Parameters and buffers on the module will be lifted into graph inputs,
|
| 1557 |
+
graph_inputs = (*parameters, *buffers, *user_inputs)
|
| 1558 |
+
(3) The graph will be fully functionalized
|
| 1559 |
+
(4) Any input mutations will be converted into additional outputs in the graph,
|
| 1560 |
+
meaning whoever calls this graph is responsible for applying the mutations
|
| 1561 |
+
back to the original inputs.
|
| 1562 |
+
(5) If is_joint is provided the graph will return parameter gradients in addition to user outputs.
|
| 1563 |
+
The graph output will look like:
|
| 1564 |
+
graph_outputs = (*updated_inputs, *user_outputs, *param_gradients)
|
| 1565 |
+
|
| 1566 |
+
There are also several restrictions on what modules can use this API. In particular:
|
| 1567 |
+
(1) If trace_joint is specified, we expect the loss function to be **fused**
|
| 1568 |
+
into the module forward. One of the outputs to the forward must be a scalar loss,
|
| 1569 |
+
which is specified with `output_loss_index`.
|
| 1570 |
+
All other outputs to the forward are presumed to not require gradients.
|
| 1571 |
+
(2) This API cannot capture optimizers (although in theory we could build an API for this).
|
| 1572 |
+
(3) Metadata mutations on params/buffers/inputs are banned.
|
| 1573 |
+
(4) Data mutations on anything that requires gradients are banned (parameters)
|
| 1574 |
+
(5) If an input is mutated, it is not allowed to alias any other inputs.
|
| 1575 |
+
(6) Parameters must not be duplicated.
|
| 1576 |
+
"""
|
| 1577 |
+
if pre_dispatch and trace_joint:
|
| 1578 |
+
raise RuntimeError("pre_dispatch is not supported when trace_joint is True.")
|
| 1579 |
+
named_parameters = dict(mod.named_parameters(remove_duplicate=False))
|
| 1580 |
+
named_buffers = dict(mod.named_buffers(remove_duplicate=False))
|
| 1581 |
+
|
| 1582 |
+
params_and_buffers = {
|
| 1583 |
+
**dict(named_parameters),
|
| 1584 |
+
**dict(named_buffers),
|
| 1585 |
+
}
|
| 1586 |
+
params_and_buffers_flat, params_spec = pytree.tree_flatten(params_and_buffers)
|
| 1587 |
+
params_and_buffers_flat = tuple(params_and_buffers_flat)
|
| 1588 |
+
params_len = len(params_and_buffers_flat)
|
| 1589 |
+
|
| 1590 |
+
kwargs = kwargs or {}
|
| 1591 |
+
|
| 1592 |
+
functional_call = create_functional_call(
|
| 1593 |
+
mod, params_spec, params_len, store_orig_mod=True
|
| 1594 |
+
)
|
| 1595 |
+
|
| 1596 |
+
num_fw_outs = None
|
| 1597 |
+
|
| 1598 |
+
if trace_joint:
|
| 1599 |
+
# This helper effectively just adds some extra asserts about what the backward will look like:
|
| 1600 |
+
# Outputs must include a scalar loss, that we compute gradients w.r.t.
|
| 1601 |
+
# We don't compute gradients w.r.t. anything else: so just in case we detach()
|
| 1602 |
+
# and other output tensors.
|
| 1603 |
+
def fn_to_trace(*args: Any) -> Any:
|
| 1604 |
+
nonlocal num_fw_outs
|
| 1605 |
+
out = functional_call(*args)
|
| 1606 |
+
if output_loss_index is None:
|
| 1607 |
+
raise RuntimeError(
|
| 1608 |
+
"""\
|
| 1609 |
+
If trace_joint=Trueit is required that one of your forward outputs must be a scalar loss.
|
| 1610 |
+
You must specify the which (index) output is the loss with output_loss_index."""
|
| 1611 |
+
)
|
| 1612 |
+
if isinstance(out, (torch.Tensor)):
|
| 1613 |
+
out = (out,)
|
| 1614 |
+
if not isinstance(out, (tuple, list)):
|
| 1615 |
+
raise RuntimeError(
|
| 1616 |
+
f"Expected forward output to be either a tensor or a list/tuple of tensors. found {type(out)}"
|
| 1617 |
+
)
|
| 1618 |
+
|
| 1619 |
+
for i, o in enumerate(out):
|
| 1620 |
+
# We only want to create a backward graph w.r.t. the loss that the user passed in.
|
| 1621 |
+
# This implies that every other output should not require gradients.
|
| 1622 |
+
# Instead of making this an error (and forcing the user to detach all other outputs
|
| 1623 |
+
# of their forward),
|
| 1624 |
+
# we'll automatically detach them here.
|
| 1625 |
+
if o.requires_grad and i != output_loss_index:
|
| 1626 |
+
raise RuntimeError(
|
| 1627 |
+
f"""\
|
| 1628 |
+
Found an output of the forward that requires gradients, that was not the scalar loss.
|
| 1629 |
+
We require all outputs to the forward that are not the scalar loss to not require gradient,
|
| 1630 |
+
because we will only compute a backward graph against the scalar loss.
|
| 1631 |
+
You can fix this by calling .detach() on each of your forward outputs that is not the loss.
|
| 1632 |
+
You specified that output index {output_loss_index} is the loss, but we found that
|
| 1633 |
+
the output at index {i} requires gradients."""
|
| 1634 |
+
)
|
| 1635 |
+
out_loss = out[output_loss_index]
|
| 1636 |
+
num_fw_outs = len(out)
|
| 1637 |
+
if not out_loss.requires_grad:
|
| 1638 |
+
raise RuntimeError(
|
| 1639 |
+
f"""\
|
| 1640 |
+
The output at index {output_loss_index} was marked as the loss, but it does not require gradients"""
|
| 1641 |
+
)
|
| 1642 |
+
if out_loss.numel() != 1:
|
| 1643 |
+
raise RuntimeError(
|
| 1644 |
+
f"""\
|
| 1645 |
+
We require the output marked as the loss (at index {output_loss_index}) to be a scalar, but it has shape {out_loss.shape}"""
|
| 1646 |
+
)
|
| 1647 |
+
return out
|
| 1648 |
+
|
| 1649 |
+
ctx = nullcontext
|
| 1650 |
+
else:
|
| 1651 |
+
# Run under no_grad, so our tracing machinery only traces an inference graph.
|
| 1652 |
+
# However if pre_dispatch=True, we want to correctly trace set_grad_enabled calls for training.
|
| 1653 |
+
ctx = nullcontext if pre_dispatch else torch.no_grad
|
| 1654 |
+
fn_to_trace = functional_call
|
| 1655 |
+
|
| 1656 |
+
full_args = []
|
| 1657 |
+
# First, the params
|
| 1658 |
+
# NB: It is REQUIRED that parameters come first, Inductor infers "fixed"
|
| 1659 |
+
# parameters by looking at the difference in parameter count outside
|
| 1660 |
+
# and inside AOTAutograd, and assumes the prefix of arguments are fixed
|
| 1661 |
+
# arguments
|
| 1662 |
+
full_args.extend(params_and_buffers_flat)
|
| 1663 |
+
# Next, the input args
|
| 1664 |
+
full_args.extend(args)
|
| 1665 |
+
|
| 1666 |
+
with ctx():
|
| 1667 |
+
fx_g, metadata, in_spec, out_spec = _aot_export_function(
|
| 1668 |
+
fn_to_trace,
|
| 1669 |
+
tuple(full_args),
|
| 1670 |
+
decompositions=decompositions,
|
| 1671 |
+
num_params_buffers=params_len,
|
| 1672 |
+
no_tangents=True,
|
| 1673 |
+
pre_dispatch=pre_dispatch,
|
| 1674 |
+
dynamic_shapes=dynamic_shapes,
|
| 1675 |
+
trace_joint=trace_joint,
|
| 1676 |
+
kwargs=kwargs,
|
| 1677 |
+
)
|
| 1678 |
+
|
| 1679 |
+
# TODO: subsume this path with the aot_stage2_graph_capture path
|
| 1680 |
+
if trace_joint:
|
| 1681 |
+
|
| 1682 |
+
@wraps(functional_call)
|
| 1683 |
+
def flattened_joint(*args: Any) -> Any:
|
| 1684 |
+
# The idea here is that the joint graph that AOTAutograd creates has some strict properties:
|
| 1685 |
+
# (1) It accepts two arguments (primals, tangents), and pytree_flattens them
|
| 1686 |
+
# (2) It returns a tuple of (fw_outs, gradients)
|
| 1687 |
+
# This is a very useful convention for anyone who wants to partition the joint graph
|
| 1688 |
+
# into a separate forward and backward graph.
|
| 1689 |
+
# However,
|
| 1690 |
+
# (1) for people exporting a single joint graph, it would be preferable not to have
|
| 1691 |
+
# any pytrees in the graph.
|
| 1692 |
+
# (2) We are guaranteed in the aot_export_module case that the forward outputs a loss,
|
| 1693 |
+
# and there are therefore no tangents that are needed to run the joint graph.
|
| 1694 |
+
# (3) AOTAutograd creates a grad_input for every input in the forward,
|
| 1695 |
+
# including None's for inputs that are not grad-requiring tensors.
|
| 1696 |
+
# we don't want these in our export graph.
|
| 1697 |
+
# and there are therefore no tangents that are needed to run the joint graph.
|
| 1698 |
+
# This function "fixes" both of the above by removing any tangent inputs,
|
| 1699 |
+
# and removing pytrees from the original FX graph.
|
| 1700 |
+
fake_tangents = [
|
| 1701 |
+
None
|
| 1702 |
+
for _ in range(
|
| 1703 |
+
metadata.num_outputs + metadata.num_mutated_inp_runtime_indices
|
| 1704 |
+
)
|
| 1705 |
+
]
|
| 1706 |
+
fw_outs, gradients = fx_g(args, fake_tangents)
|
| 1707 |
+
if len(gradients) != len(args):
|
| 1708 |
+
raise AssertionError(
|
| 1709 |
+
f"len(gradients)={len(gradients)} != len(args)={len(args)}"
|
| 1710 |
+
)
|
| 1711 |
+
output_gradients = []
|
| 1712 |
+
for a, grad in zip(args, gradients):
|
| 1713 |
+
if isinstance(a, torch.Tensor) and a.requires_grad:
|
| 1714 |
+
if grad is None:
|
| 1715 |
+
raise AssertionError("""\
|
| 1716 |
+
Found a parameter that did not receive a gradient.
|
| 1717 |
+
"This is most likely a bug, but if this needs to be supported please comment on this Github issue:
|
| 1718 |
+
https://github.com/pytorch/pytorch/issues/101192
|
| 1719 |
+
""")
|
| 1720 |
+
output_gradients.append(grad)
|
| 1721 |
+
else:
|
| 1722 |
+
if grad is not None:
|
| 1723 |
+
raise AssertionError(
|
| 1724 |
+
f"expected grad to be None for non-tensor or non-requires_grad input, got {type(grad)}"
|
| 1725 |
+
)
|
| 1726 |
+
return *fw_outs, *output_gradients
|
| 1727 |
+
|
| 1728 |
+
fx_g = make_fx(flattened_joint, record_module_stack=True)(*full_args)
|
| 1729 |
+
|
| 1730 |
+
user_args_flat = pytree.arg_tree_leaves(*args, **kwargs)
|
| 1731 |
+
if out_spec is None:
|
| 1732 |
+
raise AssertionError("out_spec must not be None")
|
| 1733 |
+
return fx_g, create_graph_signature(
|
| 1734 |
+
# type: ignore[bad-argument-type]
|
| 1735 |
+
fx_g,
|
| 1736 |
+
metadata,
|
| 1737 |
+
in_spec,
|
| 1738 |
+
out_spec,
|
| 1739 |
+
user_args_flat=user_args_flat,
|
| 1740 |
+
params_and_buffers_flat=list(params_and_buffers_flat),
|
| 1741 |
+
param_names=list(named_parameters.keys()),
|
| 1742 |
+
buffer_names=list(named_buffers.keys()),
|
| 1743 |
+
trace_joint=trace_joint,
|
| 1744 |
+
num_user_fw_outs=num_fw_outs,
|
| 1745 |
+
loss_index=output_loss_index,
|
| 1746 |
+
)
|
| 1747 |
+
|
| 1748 |
+
|
| 1749 |
+
def aot_export_joint_simple(
|
| 1750 |
+
func: Callable[..., Any],
|
| 1751 |
+
args: tuple[Any, ...],
|
| 1752 |
+
*,
|
| 1753 |
+
trace_joint: bool,
|
| 1754 |
+
# It looks like the main consequence of this API is that for dynamic shapes,
|
| 1755 |
+
# it will assume that params/buffers are static.
|
| 1756 |
+
# With the new inferred dynamic shapes API, maybe this doesn't matter?
|
| 1757 |
+
num_params_buffers: int = 0,
|
| 1758 |
+
decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
|
| 1759 |
+
) -> Callable[..., Any]:
|
| 1760 |
+
"""
|
| 1761 |
+
A simplified version of export. Used by higher order operators.
|
| 1762 |
+
|
| 1763 |
+
This function makes a high-level "no calling convention changes" guarantee:
|
| 1764 |
+
- If no inputs require grad (so we export an inference graph),
|
| 1765 |
+
there are *no* calling convention change between the exported graph, and "func".
|
| 1766 |
+
- If at least one input requires grad (so we trace out and export a joint fw-bw graph),
|
| 1767 |
+
Then if you were partition the graph into a separate forward and backward graph,
|
| 1768 |
+
The forward graph will have no calling convention changes compared to "func".
|
| 1769 |
+
|
| 1770 |
+
The above also relies on some strong restrictions around which functions this API accepts:
|
| 1771 |
+
(1) `args` cannot contain any pytrees (they must have been pytree_flattened already)
|
| 1772 |
+
(2) `func` cannot mutate any inputs
|
| 1773 |
+
(3) The outputs of `func` cannot alias any inputs.
|
| 1774 |
+
|
| 1775 |
+
Note: this function is only lightly tested today. It will probably be tested more heavily by higher order ops.
|
| 1776 |
+
"""
|
| 1777 |
+
if trace_joint:
|
| 1778 |
+
ctx = nullcontext
|
| 1779 |
+
else:
|
| 1780 |
+
# Run under no_grad, so our tracing machinery only traces an inference graph.
|
| 1781 |
+
ctx = torch.no_grad
|
| 1782 |
+
|
| 1783 |
+
with ctx():
|
| 1784 |
+
fx_g, metadata, in_spec, out_spec = _aot_export_function(
|
| 1785 |
+
func,
|
| 1786 |
+
args,
|
| 1787 |
+
decompositions=decompositions,
|
| 1788 |
+
trace_joint=trace_joint,
|
| 1789 |
+
)
|
| 1790 |
+
in_spec, _kw_in_spec = in_spec.children()
|
| 1791 |
+
# At this point, we can just directly return the (joint or inference graph) that we traced.
|
| 1792 |
+
# First though: a bunch of assertions to make sure that our graph doesn't require
|
| 1793 |
+
# any calling convention changes compared to the original function.
|
| 1794 |
+
# These restrictions are *in addition to* the general restrictions on export.
|
| 1795 |
+
|
| 1796 |
+
# No input mutations
|
| 1797 |
+
if (
|
| 1798 |
+
len([x for x in metadata.input_info if x.mutates_data or x.mutates_metadata])
|
| 1799 |
+
!= 0
|
| 1800 |
+
):
|
| 1801 |
+
raise RuntimeError(
|
| 1802 |
+
f"aot_export_joint_simple does not support input mutations. {str(metadata)}"
|
| 1803 |
+
)
|
| 1804 |
+
# No output aliasing
|
| 1805 |
+
if (
|
| 1806 |
+
len([x for x in metadata.output_info if x.output_type != OutputType.non_alias])
|
| 1807 |
+
!= 0
|
| 1808 |
+
):
|
| 1809 |
+
raise RuntimeError(
|
| 1810 |
+
f"aot_export_joint_simple does not support outputs that alias inputs. {str(metadata)}"
|
| 1811 |
+
)
|
| 1812 |
+
# No pytrees
|
| 1813 |
+
if in_spec.is_leaf():
|
| 1814 |
+
raise RuntimeError(
|
| 1815 |
+
f"aot_export_joint_simple requires inputs to be a single list/tuple. in_spec={str(in_spec)}"
|
| 1816 |
+
)
|
| 1817 |
+
if not all(child.is_leaf() for child in in_spec.children()):
|
| 1818 |
+
raise RuntimeError(
|
| 1819 |
+
f"aot_export_joint_simple requires individual inputs not to be pytrees. in_spec={str(in_spec)}"
|
| 1820 |
+
)
|
| 1821 |
+
|
| 1822 |
+
if out_spec is None:
|
| 1823 |
+
raise AssertionError("out_spec must not be None")
|
| 1824 |
+
if out_spec.is_leaf():
|
| 1825 |
+
raise RuntimeError(
|
| 1826 |
+
f"aot_export_joint_simple requires outputs to be a single list/tuple. out_spec={str(out_spec)}"
|
| 1827 |
+
)
|
| 1828 |
+
if not all(child.is_leaf() for child in out_spec.children()):
|
| 1829 |
+
raise RuntimeError(
|
| 1830 |
+
f"aot_export_joint_simple requires individual outputs not to be pytrees. out_spec={str(out_spec)}"
|
| 1831 |
+
)
|
| 1832 |
+
# TODO: we might have to temporarily patch config.functionalize_rng
|
| 1833 |
+
# so that it doesn't run when we're exporting a higher order op.
|
| 1834 |
+
|
| 1835 |
+
if config.debug_assert:
|
| 1836 |
+
# Smoke test that after partitioning, we can run the forward without any calling convention changes.
|
| 1837 |
+
fw_module, _bw_module = default_partition( # noqa: F821
|
| 1838 |
+
# type: ignore[bad-argument-type]
|
| 1839 |
+
fx_g,
|
| 1840 |
+
args,
|
| 1841 |
+
# type: ignore[unknown-name]
|
| 1842 |
+
num_fwd_outputs=len(fw_metadata.output_infos), # noqa: F821
|
| 1843 |
+
)
|
| 1844 |
+
# Attempt to run the fw_module with the original user inputs
|
| 1845 |
+
fake_mode = detect_fake_mode(args)
|
| 1846 |
+
if fake_mode is None:
|
| 1847 |
+
fake_mode = FakeTensorMode()
|
| 1848 |
+
with fake_mode:
|
| 1849 |
+
fw_module(*args)
|
| 1850 |
+
return fx_g
|
| 1851 |
+
|
| 1852 |
+
|
| 1853 |
+
# Private for now because we aren't providing a contract on what to return
|
| 1854 |
+
# for joint graphs (we could when there's a clearer use case)
|
| 1855 |
+
# In the future, we may need to add more export API's that provide their own strong guarantees.
|
| 1856 |
+
# This is meant as a general helper function for handling various export-y use cases.
|
| 1857 |
+
def _aot_export_function(
|
| 1858 |
+
func: Callable[..., Any],
|
| 1859 |
+
args: tuple[Any, ...],
|
| 1860 |
+
*,
|
| 1861 |
+
num_params_buffers: int = 0,
|
| 1862 |
+
decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
|
| 1863 |
+
# If we're exporting a joint graph and we don't want any tangent inputs in the graph
|
| 1864 |
+
# (because we are backpropping through a scalar 1 loss),
|
| 1865 |
+
# we need to explicitly specify not to include tangents in the graph.
|
| 1866 |
+
# It's not enough just to check that our tangent is a scalar, since we also
|
| 1867 |
+
# need to know if it is a 1 (no need to make it a graph input), or something else
|
| 1868 |
+
# (requiring it to be a graph input).
|
| 1869 |
+
# We don't know this info at trace time though, so we need to make it an explicit config.
|
| 1870 |
+
no_tangents: bool = False,
|
| 1871 |
+
pre_dispatch: bool = False,
|
| 1872 |
+
# If None, `dynamic_shapes` will be inferred from inputs, but the inferred result might be wrong.
|
| 1873 |
+
dynamic_shapes: bool | None = None,
|
| 1874 |
+
keep_input_mutations: bool = False,
|
| 1875 |
+
# Under export, configures whether we are getting inference or training IR
|
| 1876 |
+
trace_joint: bool = False,
|
| 1877 |
+
kwargs: dict[str, Any] | None = None,
|
| 1878 |
+
) -> tuple[
|
| 1879 |
+
Callable[..., Any], ViewAndMutationMeta, pytree.TreeSpec, pytree.TreeSpec | None
|
| 1880 |
+
]:
|
| 1881 |
+
kwargs = kwargs or {}
|
| 1882 |
+
|
| 1883 |
+
flat_fn, out_spec = create_tree_flattened_fn(func, args, kwargs)
|
| 1884 |
+
flat_args, in_spec = pytree.tree_flatten((args, kwargs))
|
| 1885 |
+
|
| 1886 |
+
fake_mode = None
|
| 1887 |
+
if dynamic_shapes is None:
|
| 1888 |
+
# Try to infer `dynamic_shapes from inputs and graph nodes
|
| 1889 |
+
fake_mode = detect_fake_mode(flat_args)
|
| 1890 |
+
if (
|
| 1891 |
+
fake_mode is None
|
| 1892 |
+
and hasattr(func, "_orig_mod")
|
| 1893 |
+
and isinstance(func._orig_mod, torch.fx.GraphModule)
|
| 1894 |
+
):
|
| 1895 |
+
vals = [
|
| 1896 |
+
node.meta["val"]
|
| 1897 |
+
for node in func._orig_mod.graph.nodes
|
| 1898 |
+
if "val" in node.meta
|
| 1899 |
+
]
|
| 1900 |
+
fake_mode = detect_fake_mode(vals)
|
| 1901 |
+
dynamic_shapes = fake_mode is not None and fake_mode.shape_env is not None
|
| 1902 |
+
|
| 1903 |
+
# The export use case doesn't care about several bits of AOTConfig
|
| 1904 |
+
# (1) compilers (we just export the graph)
|
| 1905 |
+
# (2) partitioners (export is only full graph, user can partition themselves)
|
| 1906 |
+
aot_config = AOTConfig( # type: ignore[arg-type]
|
| 1907 |
+
fw_compiler=None,
|
| 1908 |
+
bw_compiler=None,
|
| 1909 |
+
inference_compiler=None,
|
| 1910 |
+
partition_fn=None,
|
| 1911 |
+
decompositions=decompositions,
|
| 1912 |
+
num_params_buffers=num_params_buffers,
|
| 1913 |
+
aot_id=next(AOT_COUNTER),
|
| 1914 |
+
keep_inference_input_mutations=keep_input_mutations,
|
| 1915 |
+
dynamic_shapes=dynamic_shapes,
|
| 1916 |
+
aot_autograd_arg_pos_to_source=None,
|
| 1917 |
+
is_export=True,
|
| 1918 |
+
no_tangents=no_tangents,
|
| 1919 |
+
pre_dispatch=pre_dispatch,
|
| 1920 |
+
export_trace_joint=trace_joint,
|
| 1921 |
+
)
|
| 1922 |
+
if fake_mode is None:
|
| 1923 |
+
fake_mode, shape_env = construct_fake_mode(flat_args, aot_config)
|
| 1924 |
+
else:
|
| 1925 |
+
shape_env = fake_mode.shape_env
|
| 1926 |
+
fake_flat_args, act_input_indices = process_inputs(
|
| 1927 |
+
flat_args, aot_config, fake_mode, shape_env
|
| 1928 |
+
)
|
| 1929 |
+
# TODO: Improve the descs here with pytree information
|
| 1930 |
+
fake_flat_args_descs: list[AOTInput] = [
|
| 1931 |
+
PlainAOTInput(i) for i in range(len(fake_flat_args))
|
| 1932 |
+
]
|
| 1933 |
+
|
| 1934 |
+
with contextlib.ExitStack() as stack:
|
| 1935 |
+
aot_state = create_aot_state(
|
| 1936 |
+
stack,
|
| 1937 |
+
flat_fn,
|
| 1938 |
+
fake_flat_args,
|
| 1939 |
+
fake_flat_args_descs,
|
| 1940 |
+
aot_config,
|
| 1941 |
+
fake_mode,
|
| 1942 |
+
shape_env,
|
| 1943 |
+
)
|
| 1944 |
+
aot_state.fw_metadata.act_input_indices = act_input_indices
|
| 1945 |
+
aot_graph_capture = aot_stage1_graph_capture(aot_state, flat_fn)
|
| 1946 |
+
fx_g, meta = aot_stage2_export(aot_state, aot_graph_capture)
|
| 1947 |
+
|
| 1948 |
+
return fx_g, meta, in_spec, out_spec.spec
|
| 1949 |
+
|
| 1950 |
+
|
| 1951 |
+
compiled_function = aot_function
|
| 1952 |
+
compiled_module = aot_module
|
venv/lib/python3.14/site-packages/torch/_functorch/apis.py
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTE: We allow Dynamo to see this file (via torch/_dynamo/trace_rules.py) so that it can
|
| 2 |
+
# trace through functorch transforms.
|
| 3 |
+
# Currently, we can't allow Dynamo to see `eager_transforms.py`/`vmap.py` as that break a lot of thing
|
| 4 |
+
# and there isn't a mechanism to selectively expose only some functions (eg. grad) from a file
|
| 5 |
+
# to Dynamo.
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import functools
|
| 10 |
+
from typing import Any, TYPE_CHECKING
|
| 11 |
+
from typing_extensions import ParamSpec, TypeVar
|
| 12 |
+
|
| 13 |
+
from torch._functorch.utils import argnums_t, exposed_in
|
| 14 |
+
from torch._functorch.vmap import (
|
| 15 |
+
_check_out_dims_is_int_or_int_pytree,
|
| 16 |
+
_check_randomness_arg,
|
| 17 |
+
_chunked_vmap,
|
| 18 |
+
_process_batched_inputs,
|
| 19 |
+
Callable,
|
| 20 |
+
in_dims_t,
|
| 21 |
+
out_dims_t,
|
| 22 |
+
vmap_impl,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
from collections.abc import Iterable
|
| 28 |
+
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
_P = ParamSpec("_P")
|
| 32 |
+
_R = TypeVar("_R")
|
| 33 |
+
# vmap(func)(inputs) wraps all Tensor inputs to be batched in BatchedTensors,
|
| 34 |
+
# sends those into func, and then unwraps the output BatchedTensors. Operations
|
| 35 |
+
# on BatchedTensors perform the batched operations that the user is asking for.
|
| 36 |
+
#
|
| 37 |
+
# vmap's randomness behavior differs from JAX's, which would require a PRNG key
|
| 38 |
+
# to be passed everywhere.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@exposed_in("torch.func")
|
| 42 |
+
def vmap(
|
| 43 |
+
func: Callable[_P, _R],
|
| 44 |
+
in_dims: in_dims_t = 0,
|
| 45 |
+
out_dims: out_dims_t = 0,
|
| 46 |
+
randomness: str = "error",
|
| 47 |
+
*,
|
| 48 |
+
chunk_size: int | None = None,
|
| 49 |
+
) -> Callable[_P, _R]:
|
| 50 |
+
"""
|
| 51 |
+
vmap is the vectorizing map; ``vmap(func)`` returns a new function that
|
| 52 |
+
maps ``func`` over some dimension of the inputs. Semantically, vmap
|
| 53 |
+
pushes the map into PyTorch operations called by ``func``, effectively
|
| 54 |
+
vectorizing those operations.
|
| 55 |
+
|
| 56 |
+
vmap is useful for handling batch dimensions: one can write a function
|
| 57 |
+
``func`` that runs on examples and then lift it to a function that can
|
| 58 |
+
take batches of examples with ``vmap(func)``. vmap can also be used to
|
| 59 |
+
compute batched gradients when composed with autograd.
|
| 60 |
+
|
| 61 |
+
.. note::
|
| 62 |
+
:func:`torch.vmap` is aliased to :func:`torch.func.vmap` for
|
| 63 |
+
convenience. Use whichever one you'd like.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
func (function): A Python function that takes one or more arguments.
|
| 67 |
+
Must return one or more Tensors.
|
| 68 |
+
in_dims (int or nested structure): Specifies which dimension of the
|
| 69 |
+
inputs should be mapped over. ``in_dims`` should have a
|
| 70 |
+
structure like the inputs. If the ``in_dim`` for a particular
|
| 71 |
+
input is None, then that indicates there is no map dimension.
|
| 72 |
+
Default: 0.
|
| 73 |
+
out_dims (int or Tuple[int]): Specifies where the mapped dimension
|
| 74 |
+
should appear in the outputs. If ``out_dims`` is a Tuple, then
|
| 75 |
+
it should have one element per output. Default: 0.
|
| 76 |
+
randomness (str): Specifies whether the randomness in this
|
| 77 |
+
vmap should be the same or different across batches. If 'different',
|
| 78 |
+
the randomness for each batch will be different. If 'same', the
|
| 79 |
+
randomness will be the same across batches. If 'error', any calls to
|
| 80 |
+
random functions will error. Default: 'error'. WARNING: this flag
|
| 81 |
+
only applies to random PyTorch operations and does not apply to
|
| 82 |
+
Python's random module or numpy randomness.
|
| 83 |
+
chunk_size (None or int): If None (default), apply a single vmap over inputs.
|
| 84 |
+
If not None, then compute the vmap :attr:`chunk_size` samples at a time.
|
| 85 |
+
Note that :attr:`chunk_size=1` is equivalent to computing the vmap with a for-loop.
|
| 86 |
+
If you run into memory issues computing the vmap, please try a non-None chunk_size.
|
| 87 |
+
|
| 88 |
+
Returns:
|
| 89 |
+
Returns a new "batched" function. It takes the same inputs as
|
| 90 |
+
``func``, except each input has an extra dimension at the index
|
| 91 |
+
specified by ``in_dims``. It takes returns the same outputs as
|
| 92 |
+
``func``, except each output has an extra dimension at the index
|
| 93 |
+
specified by ``out_dims``.
|
| 94 |
+
|
| 95 |
+
.. warning:
|
| 96 |
+
:func:`vmap` works best with functional-style code. Please do not
|
| 97 |
+
perform any side-effects in ``func``, with the exception of
|
| 98 |
+
in-place PyTorch operations. Examples of side-effects include mutating
|
| 99 |
+
Python data structures and assigning values to variables not captured
|
| 100 |
+
in ``func``.
|
| 101 |
+
|
| 102 |
+
One example of using :func:`vmap` is to compute batched dot products. PyTorch
|
| 103 |
+
doesn't provide a batched ``torch.dot`` API; instead of unsuccessfully
|
| 104 |
+
rummaging through docs, use :func:`vmap` to construct a new function.
|
| 105 |
+
|
| 106 |
+
>>> torch.dot # [D], [D] -> []
|
| 107 |
+
>>> batched_dot = torch.func.vmap(torch.dot) # [N, D], [N, D] -> [N]
|
| 108 |
+
>>> x, y = torch.randn(2, 5), torch.randn(2, 5)
|
| 109 |
+
>>> batched_dot(x, y)
|
| 110 |
+
|
| 111 |
+
:func:`vmap` can be helpful in hiding batch dimensions, leading to a simpler
|
| 112 |
+
model authoring experience.
|
| 113 |
+
|
| 114 |
+
>>> batch_size, feature_size = 3, 5
|
| 115 |
+
>>> weights = torch.randn(feature_size, requires_grad=True)
|
| 116 |
+
>>>
|
| 117 |
+
>>> def model(feature_vec):
|
| 118 |
+
>>> # Very simple linear model with activation
|
| 119 |
+
>>> return feature_vec.dot(weights).relu()
|
| 120 |
+
>>>
|
| 121 |
+
>>> examples = torch.randn(batch_size, feature_size)
|
| 122 |
+
>>> result = torch.vmap(model)(examples)
|
| 123 |
+
|
| 124 |
+
:func:`vmap` can also help vectorize computations that were previously difficult
|
| 125 |
+
or impossible to batch. One example is higher-order gradient computation.
|
| 126 |
+
The PyTorch autograd engine computes vjps (vector-Jacobian products).
|
| 127 |
+
Computing a full Jacobian matrix for some function f: R^N -> R^N usually
|
| 128 |
+
requires N calls to ``autograd.grad``, one per Jacobian row. Using :func:`vmap`,
|
| 129 |
+
we can vectorize the whole computation, computing the Jacobian in a single
|
| 130 |
+
call to ``autograd.grad``.
|
| 131 |
+
|
| 132 |
+
>>> # Setup
|
| 133 |
+
>>> N = 5
|
| 134 |
+
>>> f = lambda x: x**2
|
| 135 |
+
>>> x = torch.randn(N, requires_grad=True)
|
| 136 |
+
>>> y = f(x)
|
| 137 |
+
>>> I_N = torch.eye(N)
|
| 138 |
+
>>>
|
| 139 |
+
>>> # Sequential approach
|
| 140 |
+
>>> jacobian_rows = [torch.autograd.grad(y, x, v, retain_graph=True)[0]
|
| 141 |
+
>>> for v in I_N.unbind()]
|
| 142 |
+
>>> jacobian = torch.stack(jacobian_rows)
|
| 143 |
+
>>>
|
| 144 |
+
>>> # vectorized gradient computation
|
| 145 |
+
>>> def get_vjp(v):
|
| 146 |
+
>>> return torch.autograd.grad(y, x, v)
|
| 147 |
+
>>> jacobian = torch.vmap(get_vjp)(I_N)
|
| 148 |
+
|
| 149 |
+
:func:`vmap` can also be nested, producing an output with multiple batched dimensions
|
| 150 |
+
|
| 151 |
+
>>> torch.dot # [D], [D] -> []
|
| 152 |
+
>>> batched_dot = torch.vmap(
|
| 153 |
+
... torch.vmap(torch.dot)
|
| 154 |
+
... ) # [N1, N0, D], [N1, N0, D] -> [N1, N0]
|
| 155 |
+
>>> x, y = torch.randn(2, 3, 5), torch.randn(2, 3, 5)
|
| 156 |
+
>>> batched_dot(x, y) # tensor of size [2, 3]
|
| 157 |
+
|
| 158 |
+
If the inputs are not batched along the first dimension, ``in_dims`` specifies
|
| 159 |
+
the dimension that each inputs are batched along as
|
| 160 |
+
|
| 161 |
+
>>> torch.dot # [N], [N] -> []
|
| 162 |
+
>>> batched_dot = torch.vmap(torch.dot, in_dims=1) # [N, D], [N, D] -> [D]
|
| 163 |
+
>>> x, y = torch.randn(2, 5), torch.randn(2, 5)
|
| 164 |
+
>>> batched_dot(
|
| 165 |
+
... x, y
|
| 166 |
+
... ) # output is [5] instead of [2] if batched along the 0th dimension
|
| 167 |
+
|
| 168 |
+
If there are multiple inputs each of which is batched along different dimensions,
|
| 169 |
+
``in_dims`` must be a tuple with the batch dimension for each input as
|
| 170 |
+
|
| 171 |
+
>>> torch.dot # [D], [D] -> []
|
| 172 |
+
>>> batched_dot = torch.vmap(torch.dot, in_dims=(0, None)) # [N, D], [D] -> [N]
|
| 173 |
+
>>> x, y = torch.randn(2, 5), torch.randn(5)
|
| 174 |
+
>>> batched_dot(
|
| 175 |
+
... x, y
|
| 176 |
+
... ) # second arg doesn't have a batch dim because in_dim[1] was None
|
| 177 |
+
|
| 178 |
+
If the input is a Python struct, ``in_dims`` must be a tuple containing a struct
|
| 179 |
+
matching the shape of the input:
|
| 180 |
+
|
| 181 |
+
>>> f = lambda dict: torch.dot(dict["x"], dict["y"])
|
| 182 |
+
>>> x, y = torch.randn(2, 5), torch.randn(5)
|
| 183 |
+
>>> input = {"x": x, "y": y}
|
| 184 |
+
>>> batched_dot = torch.vmap(f, in_dims=({"x": 0, "y": None},))
|
| 185 |
+
>>> batched_dot(input)
|
| 186 |
+
|
| 187 |
+
By default, the output is batched along the first dimension. However, it can be batched
|
| 188 |
+
along any dimension by using ``out_dims``
|
| 189 |
+
|
| 190 |
+
>>> f = lambda x: x**2
|
| 191 |
+
>>> x = torch.randn(2, 5)
|
| 192 |
+
>>> batched_pow = torch.vmap(f, out_dims=1)
|
| 193 |
+
>>> batched_pow(x) # [5, 2]
|
| 194 |
+
|
| 195 |
+
For any function that uses kwargs, the returned function will not batch the kwargs but will
|
| 196 |
+
accept kwargs
|
| 197 |
+
|
| 198 |
+
>>> x = torch.randn([2, 5])
|
| 199 |
+
>>> def fn(x, scale=4.):
|
| 200 |
+
>>> return x * scale
|
| 201 |
+
>>>
|
| 202 |
+
>>> batched_pow = torch.vmap(fn)
|
| 203 |
+
>>> assert torch.allclose(batched_pow(x), x * 4)
|
| 204 |
+
>>> batched_pow(x, scale=x) # scale is not batched, output has shape [2, 2, 5]
|
| 205 |
+
|
| 206 |
+
.. note::
|
| 207 |
+
vmap does not provide general autobatching or handle variable-length
|
| 208 |
+
sequences out of the box.
|
| 209 |
+
"""
|
| 210 |
+
from torch.compiler import is_compiling
|
| 211 |
+
|
| 212 |
+
_check_randomness_arg(randomness)
|
| 213 |
+
if not (chunk_size is None or chunk_size > 0):
|
| 214 |
+
raise ValueError(
|
| 215 |
+
f"vmap: chunk_size should be None or greater than 0. (got {chunk_size})"
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
| 219 |
+
# pyrefly: ignore[bad-argument-type]
|
| 220 |
+
return vmap_impl(
|
| 221 |
+
# pyrefly: ignore[bad-argument-type]
|
| 222 |
+
func,
|
| 223 |
+
in_dims,
|
| 224 |
+
out_dims,
|
| 225 |
+
randomness,
|
| 226 |
+
chunk_size,
|
| 227 |
+
*args,
|
| 228 |
+
**kwargs,
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
if not is_compiling():
|
| 232 |
+
wrapped = functools.wraps(func)(wrapped)
|
| 233 |
+
|
| 234 |
+
return wrapped
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def chunk_vmap(
|
| 238 |
+
func: Callable[_P, _R],
|
| 239 |
+
in_dims: in_dims_t = 0,
|
| 240 |
+
out_dims: out_dims_t = 0,
|
| 241 |
+
randomness: str = "error",
|
| 242 |
+
chunks: int = 2,
|
| 243 |
+
) -> Callable[_P, _R]:
|
| 244 |
+
"""
|
| 245 |
+
chunk_vmap is the vectorizing map (vmap) using chunks of input data. It is a mix of vmap (which vectorizes
|
| 246 |
+
everything) and map (which executes things sequentially). ``chunk_vmap`` vectorizes the input with number of
|
| 247 |
+
chunks at a time. For more details about vectorizing map, see :func:`vmap`.
|
| 248 |
+
|
| 249 |
+
.. note::
|
| 250 |
+
Please use :func:`vmap` with ``chunk_size`` argument instead of this API.
|
| 251 |
+
|
| 252 |
+
Args:
|
| 253 |
+
func (function): A Python function that takes one or more arguments.
|
| 254 |
+
Must return one or more Tensors.
|
| 255 |
+
in_dims (int or nested structure): Specifies which dimension of the
|
| 256 |
+
inputs should be mapped over. ``in_dims`` should have a
|
| 257 |
+
structure like the inputs. If the ``in_dim`` for a particular
|
| 258 |
+
input is None, then that indicates there is no map dimension.
|
| 259 |
+
Default: 0.
|
| 260 |
+
out_dims (int or Tuple[int]): Specifies where the mapped dimension
|
| 261 |
+
should appear in the outputs. If ``out_dims`` is a Tuple, then
|
| 262 |
+
it should have one element per output. Default: 0.
|
| 263 |
+
randomness (str): Specifies whether the randomness in this
|
| 264 |
+
vmap should be the same or different across batches. If 'different',
|
| 265 |
+
the randomness for each batch will be different. If 'same', the
|
| 266 |
+
randomness will be the same across batches. If 'error', any calls to
|
| 267 |
+
random functions will error. Default: 'error'. WARNING: this flag
|
| 268 |
+
only applies to random PyTorch operations and does not apply to
|
| 269 |
+
Python's random module or numpy randomness.
|
| 270 |
+
chunks (int): Number of chunks to use to split the input data. Default is 2.
|
| 271 |
+
If equals to 1 then :func:`vmap` is called.
|
| 272 |
+
|
| 273 |
+
Returns:
|
| 274 |
+
Returns a new "batched" function. It takes the same inputs as
|
| 275 |
+
``func``, except each input has an extra dimension at the index
|
| 276 |
+
specified by ``in_dims``. It takes returns the same outputs as
|
| 277 |
+
``func``, except each output has an extra dimension at the index
|
| 278 |
+
specified by ``out_dims``.
|
| 279 |
+
"""
|
| 280 |
+
_check_randomness_arg(randomness)
|
| 281 |
+
|
| 282 |
+
if chunks == 1:
|
| 283 |
+
return vmap(func, in_dims=in_dims, out_dims=out_dims, randomness=randomness)
|
| 284 |
+
|
| 285 |
+
def _get_chunk_flat_args(
|
| 286 |
+
flat_args_: Iterable[Any],
|
| 287 |
+
flat_in_dims_: Iterable[int | None],
|
| 288 |
+
chunks_: int,
|
| 289 |
+
) -> Iterable[Any]:
|
| 290 |
+
flat_args_chunks = tuple(
|
| 291 |
+
t.chunk(chunks_, dim=in_dim)
|
| 292 |
+
if in_dim is not None
|
| 293 |
+
else [
|
| 294 |
+
t,
|
| 295 |
+
]
|
| 296 |
+
* chunks_
|
| 297 |
+
for t, in_dim in zip(flat_args_, flat_in_dims_)
|
| 298 |
+
)
|
| 299 |
+
# transpose chunk dim and flatten structure
|
| 300 |
+
# chunks_flat_args is a list of flatten args
|
| 301 |
+
chunks_flat_args = zip(*flat_args_chunks)
|
| 302 |
+
return chunks_flat_args
|
| 303 |
+
|
| 304 |
+
@functools.wraps(func)
|
| 305 |
+
def wrapped_with_chunks(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
| 306 |
+
_check_out_dims_is_int_or_int_pytree(out_dims, func)
|
| 307 |
+
_, flat_in_dims, flat_args, args_spec = _process_batched_inputs(
|
| 308 |
+
in_dims, args, func
|
| 309 |
+
)
|
| 310 |
+
# Chunk flat arguments
|
| 311 |
+
chunks_flat_args = _get_chunk_flat_args(flat_args, flat_in_dims, chunks)
|
| 312 |
+
|
| 313 |
+
# Apply vmap on chunks
|
| 314 |
+
return _chunked_vmap(
|
| 315 |
+
# pyrefly: ignore[bad-argument-type]
|
| 316 |
+
func,
|
| 317 |
+
flat_in_dims,
|
| 318 |
+
chunks_flat_args,
|
| 319 |
+
args_spec,
|
| 320 |
+
out_dims,
|
| 321 |
+
randomness,
|
| 322 |
+
**kwargs,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
return wrapped_with_chunks
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
# TODO: Improve the return type of this function
|
| 329 |
+
@exposed_in("torch.func")
|
| 330 |
+
def grad(
|
| 331 |
+
func: Callable[_P, Any], argnums: argnums_t = 0, has_aux: bool = False
|
| 332 |
+
) -> Callable[_P, Any]:
|
| 333 |
+
"""``grad`` operator helps computing gradients of ``func`` with respect to the
|
| 334 |
+
input(s) specified by ``argnums``. This operator can be nested to
|
| 335 |
+
compute higher-order gradients.
|
| 336 |
+
|
| 337 |
+
Args:
|
| 338 |
+
func (Callable): A Python function that takes one or more arguments.
|
| 339 |
+
Must return a single-element Tensor. If specified ``has_aux`` equals ``True``,
|
| 340 |
+
function can return a tuple of single-element Tensor and other auxiliary objects:
|
| 341 |
+
``(output, aux)``.
|
| 342 |
+
argnums (int or Tuple[int]): Specifies arguments to compute gradients with respect to.
|
| 343 |
+
``argnums`` can be single integer or tuple of integers. Default: 0.
|
| 344 |
+
has_aux (bool): Flag indicating that ``func`` returns a tensor and other
|
| 345 |
+
auxiliary objects: ``(output, aux)``. Default: False.
|
| 346 |
+
|
| 347 |
+
Returns:
|
| 348 |
+
Function to compute gradients with respect to its inputs. By default, the output of
|
| 349 |
+
the function is the gradient tensor(s) with respect to the first argument.
|
| 350 |
+
If specified ``has_aux`` equals ``True``, tuple of gradients and output auxiliary objects
|
| 351 |
+
is returned. If ``argnums`` is a tuple of integers, a tuple of output gradients with
|
| 352 |
+
respect to each ``argnums`` value is returned.
|
| 353 |
+
|
| 354 |
+
Example of using ``grad``:
|
| 355 |
+
|
| 356 |
+
>>> # xdoctest: +SKIP
|
| 357 |
+
>>> from torch.func import grad
|
| 358 |
+
>>> x = torch.randn([])
|
| 359 |
+
>>> cos_x = grad(lambda x: torch.sin(x))(x)
|
| 360 |
+
>>> assert torch.allclose(cos_x, x.cos())
|
| 361 |
+
>>>
|
| 362 |
+
>>> # Second-order gradients
|
| 363 |
+
>>> neg_sin_x = grad(grad(lambda x: torch.sin(x)))(x)
|
| 364 |
+
>>> assert torch.allclose(neg_sin_x, -x.sin())
|
| 365 |
+
|
| 366 |
+
When composed with ``vmap``, ``grad`` can be used to compute per-sample-gradients:
|
| 367 |
+
|
| 368 |
+
>>> # xdoctest: +SKIP
|
| 369 |
+
>>> from torch.func import grad, vmap
|
| 370 |
+
>>> batch_size, feature_size = 3, 5
|
| 371 |
+
>>>
|
| 372 |
+
>>> def model(weights, feature_vec):
|
| 373 |
+
>>> # Very simple linear model with activation
|
| 374 |
+
>>> assert feature_vec.dim() == 1
|
| 375 |
+
>>> return feature_vec.dot(weights).relu()
|
| 376 |
+
>>>
|
| 377 |
+
>>> def compute_loss(weights, example, target):
|
| 378 |
+
>>> y = model(weights, example)
|
| 379 |
+
>>> return ((y - target) ** 2).mean() # MSELoss
|
| 380 |
+
>>>
|
| 381 |
+
>>> weights = torch.randn(feature_size, requires_grad=True)
|
| 382 |
+
>>> examples = torch.randn(batch_size, feature_size)
|
| 383 |
+
>>> targets = torch.randn(batch_size)
|
| 384 |
+
>>> inputs = (weights, examples, targets)
|
| 385 |
+
>>> grad_weight_per_example = vmap(grad(compute_loss), in_dims=(None, 0, 0))(
|
| 386 |
+
... *inputs
|
| 387 |
+
... )
|
| 388 |
+
|
| 389 |
+
Example of using ``grad`` with ``has_aux`` and ``argnums``:
|
| 390 |
+
|
| 391 |
+
>>> # xdoctest: +SKIP
|
| 392 |
+
>>> from torch.func import grad
|
| 393 |
+
>>> def my_loss_func(y, y_pred):
|
| 394 |
+
>>> loss_per_sample = (0.5 * y_pred - y) ** 2
|
| 395 |
+
>>> loss = loss_per_sample.mean()
|
| 396 |
+
>>> return loss, (y_pred, loss_per_sample)
|
| 397 |
+
>>>
|
| 398 |
+
>>> fn = grad(my_loss_func, argnums=(0, 1), has_aux=True)
|
| 399 |
+
>>> y_true = torch.rand(4)
|
| 400 |
+
>>> y_preds = torch.rand(4, requires_grad=True)
|
| 401 |
+
>>> out = fn(y_true, y_preds)
|
| 402 |
+
>>> # > output is ((grads w.r.t y_true, grads w.r.t y_preds), (y_pred, loss_per_sample))
|
| 403 |
+
|
| 404 |
+
.. note::
|
| 405 |
+
Using PyTorch ``torch.no_grad`` together with ``grad``.
|
| 406 |
+
|
| 407 |
+
Case 1: Using ``torch.no_grad`` inside a function:
|
| 408 |
+
|
| 409 |
+
>>> # xdoctest: +SKIP
|
| 410 |
+
>>> def f(x):
|
| 411 |
+
>>> with torch.no_grad():
|
| 412 |
+
>>> c = x ** 2
|
| 413 |
+
>>> return x - c
|
| 414 |
+
|
| 415 |
+
In this case, ``grad(f)(x)`` will respect the inner ``torch.no_grad``.
|
| 416 |
+
|
| 417 |
+
Case 2: Using ``grad`` inside ``torch.no_grad`` context manager:
|
| 418 |
+
|
| 419 |
+
>>> # xdoctest: +SKIP
|
| 420 |
+
>>> with torch.no_grad():
|
| 421 |
+
>>> grad(f)(x)
|
| 422 |
+
|
| 423 |
+
In this case, ``grad`` will respect the inner ``torch.no_grad``, but not the
|
| 424 |
+
outer one. This is because ``grad`` is a "function transform": its result
|
| 425 |
+
should not depend on the result of a context manager outside of ``f``.
|
| 426 |
+
|
| 427 |
+
"""
|
| 428 |
+
# To avoid cyclical dependency.
|
| 429 |
+
import torch._functorch.eager_transforms as eager_transforms
|
| 430 |
+
from torch.compiler import is_compiling
|
| 431 |
+
|
| 432 |
+
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> tuple[Any, torch.Tensor]:
|
| 433 |
+
return eager_transforms.grad_impl(func, argnums, has_aux, args, kwargs)
|
| 434 |
+
|
| 435 |
+
if not is_compiling():
|
| 436 |
+
wrapper = functools.wraps(func)(wrapper)
|
| 437 |
+
|
| 438 |
+
return wrapper
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
# TODO: Improve the return type of this function
|
| 442 |
+
@exposed_in("torch.func")
|
| 443 |
+
def grad_and_value(
|
| 444 |
+
func: Callable[_P, Any], argnums: argnums_t = 0, has_aux: bool = False
|
| 445 |
+
) -> Callable[_P, tuple[Any, Any]]:
|
| 446 |
+
"""
|
| 447 |
+
Returns a function to compute a tuple of the gradient and primal, or
|
| 448 |
+
forward, computation.
|
| 449 |
+
|
| 450 |
+
Args:
|
| 451 |
+
func (Callable): A Python function that takes one or more arguments.
|
| 452 |
+
Must return a single-element Tensor. If specified ``has_aux``
|
| 453 |
+
equals ``True``, function can return a tuple of single-element
|
| 454 |
+
Tensor and other auxiliary objects: ``(output, aux)``.
|
| 455 |
+
argnums (int or Tuple[int]): Specifies arguments to compute gradients
|
| 456 |
+
with respect to. ``argnums`` can be single integer or tuple of
|
| 457 |
+
integers. Default: 0.
|
| 458 |
+
has_aux (bool): Flag indicating that ``func`` returns a tensor and
|
| 459 |
+
other auxiliary objects: ``(output, aux)``. Default: False.
|
| 460 |
+
|
| 461 |
+
Returns:
|
| 462 |
+
Function to compute a tuple of gradients with respect to its inputs
|
| 463 |
+
and the forward computation. By default, the output of the function is
|
| 464 |
+
a tuple of the gradient tensor(s) with respect to the first argument
|
| 465 |
+
and the primal computation. If specified ``has_aux`` equals
|
| 466 |
+
``True``, tuple of gradients and tuple of the forward computation with
|
| 467 |
+
output auxiliary objects is returned. If ``argnums`` is a tuple of
|
| 468 |
+
integers, a tuple of a tuple of the output gradients with respect to
|
| 469 |
+
each ``argnums`` value and the forward computation is returned.
|
| 470 |
+
|
| 471 |
+
See :func:`grad` for examples
|
| 472 |
+
"""
|
| 473 |
+
from torch._functorch import eager_transforms
|
| 474 |
+
from torch.compiler import is_compiling
|
| 475 |
+
|
| 476 |
+
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> tuple[Any, torch.Tensor]:
|
| 477 |
+
return eager_transforms.grad_and_value_impl(
|
| 478 |
+
func, argnums, has_aux, args, kwargs
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
if not is_compiling():
|
| 482 |
+
wrapper = functools.wraps(func)(wrapper)
|
| 483 |
+
|
| 484 |
+
return wrapper
|
venv/lib/python3.14/site-packages/torch/_functorch/autograd_function.py
ADDED
|
@@ -0,0 +1,909 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, NamedTuple, TYPE_CHECKING
|
| 4 |
+
from typing_extensions import ParamSpec, TypeVar
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.utils._pytree as pytree
|
| 8 |
+
from torch._C._functorch import (
|
| 9 |
+
_unwrap_for_grad,
|
| 10 |
+
_wrap_for_grad,
|
| 11 |
+
current_level,
|
| 12 |
+
TransformType,
|
| 13 |
+
)
|
| 14 |
+
from torch._functorch.apis import vmap
|
| 15 |
+
from torch._functorch.utils import enable_single_level_autograd_function
|
| 16 |
+
from torch._functorch.vmap import (
|
| 17 |
+
_add_batch_dim,
|
| 18 |
+
_broadcast_to_and_flatten,
|
| 19 |
+
restore_vmap,
|
| 20 |
+
unwrap_batched,
|
| 21 |
+
wrap_batched,
|
| 22 |
+
)
|
| 23 |
+
from torch._ops import HigherOrderOperator
|
| 24 |
+
from torch.autograd.forward_ad import _set_fwd_grad_enabled
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if TYPE_CHECKING:
|
| 28 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 29 |
+
|
| 30 |
+
from torch._functorch.pyfunctorch import FuncTorchInterpreter, VmapInterpreter
|
| 31 |
+
|
| 32 |
+
_P = ParamSpec("_P")
|
| 33 |
+
_R = TypeVar("_R")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# autograd.Function technically runs before the regular PyTorch dispatcher.
|
| 37 |
+
# This is how features like autocast and torch_dispatch (e.g. PythonTLSSnapshot)
|
| 38 |
+
# work with it. One day we might decide to change this, but until then,
|
| 39 |
+
# we need to give the illusion that autograd.Function runs before those things.
|
| 40 |
+
#
|
| 41 |
+
# We do this by using creating a custom HigherOrderOperator that only functorch
|
| 42 |
+
# dispatches specially.
|
| 43 |
+
class CustomFunctionHigherOrderOperator(HigherOrderOperator):
|
| 44 |
+
def __init__(self) -> None:
|
| 45 |
+
super().__init__("custom_function_call")
|
| 46 |
+
|
| 47 |
+
def __call__(
|
| 48 |
+
self,
|
| 49 |
+
autograd_function: type[torch.autograd.Function],
|
| 50 |
+
*args: _P.args,
|
| 51 |
+
**kwargs: _P.kwargs,
|
| 52 |
+
) -> Any:
|
| 53 |
+
# When custom_function_call is done dispatching through functorch,
|
| 54 |
+
# it should just invoke the autograd.Function. This is consistent
|
| 55 |
+
# with the autograd.Function behavior of being invoked before the
|
| 56 |
+
# PyTorch dispatcher.
|
| 57 |
+
#
|
| 58 |
+
# This will lead us into trouble later down the line, but this is
|
| 59 |
+
# pre-existing. There is an invariant that a function traced by
|
| 60 |
+
# make_fx should have the same behavior when provided the same
|
| 61 |
+
# Tensor. However, make_fx sees autograd.Function as a composite
|
| 62 |
+
# (because autograd.Function happens before the Python dispatch key)
|
| 63 |
+
# and only traces the forward pass.
|
| 64 |
+
if torch._C._are_functorch_transforms_active():
|
| 65 |
+
# pyrefly: ignore [missing-attribute]
|
| 66 |
+
return super().__call__(autograd_function, *args, **kwargs)
|
| 67 |
+
return autograd_function.apply(*args, **kwargs)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# "custom_function_call"
|
| 71 |
+
# This is the mechanism for an autograd.Function that works with functorch transforms.
|
| 72 |
+
# It wraps an autograd.Function; interactions with functorch transforms are defined
|
| 73 |
+
# via PyDispatcher and HigherOrderOperator rather than through the traditional PyTorch
|
| 74 |
+
# dispatcher.
|
| 75 |
+
custom_function_call = CustomFunctionHigherOrderOperator()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# The grad rule for custom_function_call is to construct a new _SingleLevelFunction
|
| 79 |
+
# (autograd.Function that only works with a single layer (level) of functorch) that:
|
| 80 |
+
# - unwraps the inputs
|
| 81 |
+
# - redispatches to custom_function_call
|
| 82 |
+
# - wraps the outputs
|
| 83 |
+
# and whose backward pass calls the original autograd.Function's backward.
|
| 84 |
+
#
|
| 85 |
+
# Why do we need to redispatch to custom_function_call?
|
| 86 |
+
# -----------------------------------------------------
|
| 87 |
+
# This is consistent with how ATen operators work with functorch's grad transform:
|
| 88 |
+
# they always redispatch to the original operator.
|
| 89 |
+
# Consider torch.sin, and let's say we do grad0(grad1(torch.sin))(x)
|
| 90 |
+
#
|
| 91 |
+
# grad1 will:
|
| 92 |
+
# - set up the autograd graph
|
| 93 |
+
# - unwrap the inputs
|
| 94 |
+
# - redispatch to at::sin (*)
|
| 95 |
+
# - rewrap the outputs on the return
|
| 96 |
+
#
|
| 97 |
+
# On the redispatch in (*), grad0 will:
|
| 98 |
+
# - set up the autograd graph
|
| 99 |
+
# - unwrap the inputs
|
| 100 |
+
# - redispatch to at::sin
|
| 101 |
+
# - rewrap the outputs on the return
|
| 102 |
+
#
|
| 103 |
+
# To "set up the autograd graph", we generate a _SingleLevelFunction
|
| 104 |
+
# and apply it.
|
| 105 |
+
@custom_function_call.py_impl(TransformType.Grad)
|
| 106 |
+
@custom_function_call.py_impl(TransformType.Jvp)
|
| 107 |
+
def custom_function_call_grad(
|
| 108 |
+
interpreter: FuncTorchInterpreter,
|
| 109 |
+
autograd_function: type[torch.autograd.Function],
|
| 110 |
+
*operands: Any,
|
| 111 |
+
) -> Any:
|
| 112 |
+
Generated = generate_single_level_function(interpreter, autograd_function)
|
| 113 |
+
with enable_single_level_autograd_function():
|
| 114 |
+
# pyrefly: ignore [missing-attribute]
|
| 115 |
+
flat_out = Generated.apply(*operands)
|
| 116 |
+
return flat_out
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def generate_single_level_function(
|
| 120 |
+
interpreter: FuncTorchInterpreter,
|
| 121 |
+
autograd_function: type[torch.autograd.Function],
|
| 122 |
+
) -> type[torch.autograd.function._SingleLevelFunction]:
|
| 123 |
+
level = interpreter.level()
|
| 124 |
+
|
| 125 |
+
def forward(*operands: Any) -> Any:
|
| 126 |
+
unwrapped_operands = pytree.tree_map_only(
|
| 127 |
+
torch.Tensor, lambda x: _unwrap_for_grad(x, level), operands
|
| 128 |
+
)
|
| 129 |
+
# Both enable_grad() and _set_fwd_grad_enabled() are necessary no matter
|
| 130 |
+
# the transform. _SingleLevelFunction will turn off both fwd and bwd
|
| 131 |
+
# gradient computation and we need to turn it back on here.
|
| 132 |
+
with torch.enable_grad(), _set_fwd_grad_enabled(True), interpreter.lower():
|
| 133 |
+
unwrapped_output = custom_function_call(
|
| 134 |
+
autograd_function, *unwrapped_operands
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# See NOTE [mark_dirty object identity check]
|
| 138 |
+
def wrap_fn(output: torch.Tensor) -> torch.Tensor:
|
| 139 |
+
return _wrap_for_grad(output, level)
|
| 140 |
+
|
| 141 |
+
return wrap_outputs_maintaining_identity(
|
| 142 |
+
unwrapped_output, unwrapped_operands, operands, wrap_fn
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def setup_context(ctx: Any, inputs: Any, output: Any) -> Any:
|
| 146 |
+
return autograd_function.setup_context(ctx, inputs, output)
|
| 147 |
+
|
| 148 |
+
# backward is only used if the transform is TransformType.Grad
|
| 149 |
+
def backward(ctx: Any, *grads: Any) -> Any:
|
| 150 |
+
result = autograd_function.backward(ctx, *grads)
|
| 151 |
+
return result
|
| 152 |
+
|
| 153 |
+
# jvp is only used if the transform is TransformType.Jvp
|
| 154 |
+
def jvp(ctx: Any, *tangents: Any) -> Any:
|
| 155 |
+
result = autograd_function.jvp(ctx, *tangents)
|
| 156 |
+
return result
|
| 157 |
+
|
| 158 |
+
# This is the sequence of magic words to dynamically generate a Subclass with
|
| 159 |
+
# a given name. A Tensor's .grad_fn field has a class name that is the original
|
| 160 |
+
# autograd.Function's name + Backward, so we do this to generate some
|
| 161 |
+
# meaningful name.
|
| 162 |
+
name = f"{autograd_function.__name__}Generated"
|
| 163 |
+
Generated = type(
|
| 164 |
+
name,
|
| 165 |
+
(torch.autograd.function._SingleLevelFunction,),
|
| 166 |
+
{
|
| 167 |
+
"forward": staticmethod(forward),
|
| 168 |
+
"backward": staticmethod(backward),
|
| 169 |
+
"jvp": staticmethod(jvp),
|
| 170 |
+
"setup_context": staticmethod(setup_context),
|
| 171 |
+
},
|
| 172 |
+
)
|
| 173 |
+
return Generated
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# wrap_outputs_maintaining_identity handles outputs from the vmap,
|
| 177 |
+
# backward (vjp), and jvp staticmethod. The way it distinguishes
|
| 178 |
+
# between the vmap case and the {backward, jvp} case is if the out_dims
|
| 179 |
+
# are specified or not.
|
| 180 |
+
#
|
| 181 |
+
# NB: we cannot use out_dims=None as the deciding factor. This because
|
| 182 |
+
# out_dims=None can still happen in the vmap staticmethod! What the
|
| 183 |
+
# user is saying in that case is that their output does not have a
|
| 184 |
+
# dimension that is being vmapped over, which is valid.
|
| 185 |
+
NO_OUT_DIMS = "not specified"
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# NOTE [mark_dirty object identity check]
|
| 189 |
+
# autograd.Function's ctx.mark_dirty expect a returned input
|
| 190 |
+
# to have the same object identity as the input.
|
| 191 |
+
# Mode-only functorch will greatly simplify this logic.
|
| 192 |
+
def wrap_outputs_maintaining_identity(
|
| 193 |
+
outputs: Any,
|
| 194 |
+
unwrapped_inputs: Any,
|
| 195 |
+
orig_inputs: Any,
|
| 196 |
+
wrap_fn: Callable[..., Any],
|
| 197 |
+
out_dims: Any = NO_OUT_DIMS,
|
| 198 |
+
) -> Any:
|
| 199 |
+
flat_unwrapped_inputs = pytree.arg_tree_leaves(*unwrapped_inputs)
|
| 200 |
+
flat_orig_inputs = pytree.arg_tree_leaves(*orig_inputs)
|
| 201 |
+
|
| 202 |
+
unwrapped_input_to_orig_input = {
|
| 203 |
+
id(unwrapped): orig
|
| 204 |
+
for unwrapped, orig in zip(flat_unwrapped_inputs, flat_orig_inputs)
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
flat_outputs, spec = pytree.tree_flatten(outputs)
|
| 208 |
+
result = []
|
| 209 |
+
|
| 210 |
+
out_dims_specified = out_dims != NO_OUT_DIMS
|
| 211 |
+
|
| 212 |
+
flat_out_dims = None
|
| 213 |
+
if out_dims_specified:
|
| 214 |
+
flat_out_dims = _broadcast_to_and_flatten(out_dims, spec)
|
| 215 |
+
# _broadcast_to_and_flatten returns None if it is unable to broadcast.
|
| 216 |
+
# TODO: update following link from master to stable once that's out
|
| 217 |
+
if flat_out_dims is None:
|
| 218 |
+
raise RuntimeError(
|
| 219 |
+
f"The autograd.Function's vmap staticmethod returned an "
|
| 220 |
+
f"incompatible (output, out_dims) tuple. "
|
| 221 |
+
f"Expected out_dims={out_dims} "
|
| 222 |
+
f"to be compatible with the structure of `output`. "
|
| 223 |
+
f"out_dims has structure {pytree.tree_flatten(out_dims)[1]} "
|
| 224 |
+
f"but output has structure {spec}. "
|
| 225 |
+
f"For more details, please see "
|
| 226 |
+
f"https://pytorch.org/docs/main/notes/extending.func.html"
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
for i, output in enumerate(flat_outputs):
|
| 230 |
+
if not isinstance(output, torch.Tensor):
|
| 231 |
+
result.append(output)
|
| 232 |
+
continue
|
| 233 |
+
if id(output) in unwrapped_input_to_orig_input:
|
| 234 |
+
result.append(unwrapped_input_to_orig_input[id(output)])
|
| 235 |
+
continue
|
| 236 |
+
if out_dims_specified:
|
| 237 |
+
if flat_out_dims is None:
|
| 238 |
+
raise AssertionError(
|
| 239 |
+
"flat_out_dims must not be None when out_dims is specified"
|
| 240 |
+
)
|
| 241 |
+
result.append(wrap_fn(output, flat_out_dims[i]))
|
| 242 |
+
else:
|
| 243 |
+
result.append(wrap_fn(output))
|
| 244 |
+
|
| 245 |
+
return pytree.tree_unflatten(result, spec)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
# NOTE: [functorch vjp and autograd interaction]
|
| 249 |
+
# There's an edge case with the functorch vjp and autograd interaction
|
| 250 |
+
# that will eventually be fixed by mode-only functorch.
|
| 251 |
+
# The TL;DR is that there's no way to unwrap a dead GradTensorWrapper,
|
| 252 |
+
# so we (the framework) need to do it manually. Regular PyTorch operators
|
| 253 |
+
# automatically do so this is consistent.
|
| 254 |
+
#
|
| 255 |
+
# class MyExp(torch.autograd.Function):
|
| 256 |
+
# @staticmethod
|
| 257 |
+
# def forward(x):
|
| 258 |
+
# return x.exp()
|
| 259 |
+
#
|
| 260 |
+
# @staticmethod
|
| 261 |
+
# def setup_context(ctx, inputs, output):
|
| 262 |
+
# y = output
|
| 263 |
+
# ctx.save_for_backward(y)
|
| 264 |
+
#
|
| 265 |
+
# @staticmethod
|
| 266 |
+
# def backward(gy):
|
| 267 |
+
# y, = ctx.saved_tensors()
|
| 268 |
+
# return MyMul.apply(gy, y)
|
| 269 |
+
#
|
| 270 |
+
# x = torch.randn([], requires_grad=True)
|
| 271 |
+
# gy = torch.randn([], requires_grad=True)
|
| 272 |
+
# _, vjp_fn = vjp(MySin.apply, x)
|
| 273 |
+
# result = vjp_fn(gy)
|
| 274 |
+
#
|
| 275 |
+
# MyMul is an autograd.Function that is not shown here.
|
| 276 |
+
# It saves a `y` for backward (since gy requires grad).
|
| 277 |
+
#
|
| 278 |
+
# in vjp_fn(gy), we get:
|
| 279 |
+
# > MyMul.apply(gy, GradTensorWrapper(y, level=dead))
|
| 280 |
+
# Because the y that is saved for backward by MyExp is a GradTensorWrapper
|
| 281 |
+
# but is now dead since we are outside the vjp context.
|
| 282 |
+
#
|
| 283 |
+
# PyTorch dispatcher operations, upon seeing a dead GradTensorWrapper,
|
| 284 |
+
# will automatically unwrap the GradTensorWrapper when applied.
|
| 285 |
+
# But since autograd.Function technically sits above the regular PyTorch
|
| 286 |
+
# dispatcher, it doesn't get this treatment. So we manually do
|
| 287 |
+
# the unwrapping to be consistent with regular PyTorch dispatcher operations.
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class VmapInfo(NamedTuple):
|
| 291 |
+
batch_size: int
|
| 292 |
+
randomness: str
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def has_overridden_vmap_rule(
|
| 296 |
+
autograd_function: type[torch.autograd.Function],
|
| 297 |
+
) -> bool:
|
| 298 |
+
return autograd_function.vmap is not torch.autograd.Function.vmap
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def validate_vmap_returns_tuple_of_two_elements(result: Any) -> None:
|
| 302 |
+
base_error_msg = (
|
| 303 |
+
"Expected the vmap staticmethod to have two returns, an output "
|
| 304 |
+
"and out_dims with pytree structure compatible with the output. "
|
| 305 |
+
)
|
| 306 |
+
if not isinstance(result, tuple):
|
| 307 |
+
raise RuntimeError(base_error_msg + f"Got a {type(result)} instead")
|
| 308 |
+
if not len(result) == 2:
|
| 309 |
+
raise RuntimeError(base_error_msg + f"Got {len(result)} returns instead")
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@custom_function_call.py_impl(TransformType.Vmap)
|
| 313 |
+
def custom_function_call_vmap(
|
| 314 |
+
interpreter: VmapInterpreter,
|
| 315 |
+
autograd_function: type[torch.autograd.Function],
|
| 316 |
+
*operands: Any,
|
| 317 |
+
**kwargs: Any,
|
| 318 |
+
) -> Any:
|
| 319 |
+
if any(
|
| 320 |
+
isinstance(val, torch.Tensor)
|
| 321 |
+
for val in torch.utils._pytree.tree_flatten(kwargs)[0]
|
| 322 |
+
):
|
| 323 |
+
raise NotImplementedError(
|
| 324 |
+
f"Run vmap on autograd.Function with kwarg-only Tensor args. "
|
| 325 |
+
f"Please do not pass kwarg-only Tensors to autograd.Function. "
|
| 326 |
+
f"Got: {kwargs}"
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
if autograd_function.generate_vmap_rule:
|
| 330 |
+
if has_overridden_vmap_rule(autograd_function):
|
| 331 |
+
# TODO: Update link to stable once that's out
|
| 332 |
+
# https://github.com/pytorch/pytorch/issues/92029
|
| 333 |
+
raise RuntimeError(
|
| 334 |
+
f"You tried to vmap over {autograd_function.__name__}, but "
|
| 335 |
+
f"it has both generate_vmap_rule=True and an overridden vmap "
|
| 336 |
+
f"staticmethod. Please set generate_vmap_rule=False or delete "
|
| 337 |
+
f"the overridden vmap staticmethod to avoid ambiguity. "
|
| 338 |
+
f"For more details, please see "
|
| 339 |
+
f"https://pytorch.org/docs/main/notes/extending.func.html"
|
| 340 |
+
)
|
| 341 |
+
return custom_function_call_vmap_generate_rule(
|
| 342 |
+
interpreter, autograd_function, *operands
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
if not has_overridden_vmap_rule(autograd_function):
|
| 346 |
+
# TODO: Update link to stable once that's out
|
| 347 |
+
# https://github.com/pytorch/pytorch/issues/92029
|
| 348 |
+
raise RuntimeError(
|
| 349 |
+
f"You tried to vmap over {autograd_function.__name__}, but "
|
| 350 |
+
f"it does not have vmap support. Please override and implement the "
|
| 351 |
+
f"vmap staticmethod or set generate_vmap_rule=True. "
|
| 352 |
+
f"For more details, please see "
|
| 353 |
+
f"https://pytorch.org/docs/main/notes/extending.func.html"
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
return custom_function_call_vmap_helper(
|
| 357 |
+
interpreter, autograd_function.vmap, autograd_function, *operands, **kwargs
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def custom_function_call_vmap_helper(
|
| 362 |
+
interpreter: VmapInterpreter,
|
| 363 |
+
vmap_function: Callable[..., Any],
|
| 364 |
+
op: Any,
|
| 365 |
+
*operands: Any,
|
| 366 |
+
**kwargs: Any,
|
| 367 |
+
) -> Any:
|
| 368 |
+
current_level = interpreter.level()
|
| 369 |
+
info = VmapInfo(
|
| 370 |
+
batch_size=interpreter.batch_size(),
|
| 371 |
+
randomness=interpreter.randomness(),
|
| 372 |
+
)
|
| 373 |
+
# We're either in the autograd.Function case (vmap staticmethod)
|
| 374 |
+
# or the torch.library.register_vmap case.
|
| 375 |
+
autograd_function_case = isinstance(op, torch.autograd.function.FunctionMeta)
|
| 376 |
+
|
| 377 |
+
def lower_to_next() -> Any:
|
| 378 |
+
if autograd_function_case:
|
| 379 |
+
return interpreter.lower()
|
| 380 |
+
else:
|
| 381 |
+
return torch._C._ExcludeDispatchKeyGuard(
|
| 382 |
+
torch._C.DispatchKeySet(torch._C.DispatchKey.FuncTorchBatched)
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
unwrapped_operands, in_dims = unwrap_batched(operands, current_level)
|
| 386 |
+
# If none of the tensors are batched at the current level, then we skip the
|
| 387 |
+
# current level. This saves the user from needing to handle this case in
|
| 388 |
+
# their vmap staticmethod (and is consistent with our C++ batching rule API)
|
| 389 |
+
if pytree.tree_all(lambda dim: dim is None, in_dims):
|
| 390 |
+
with lower_to_next():
|
| 391 |
+
if autograd_function_case:
|
| 392 |
+
return custom_function_call(op, *operands)
|
| 393 |
+
else:
|
| 394 |
+
return op(*operands, **kwargs)
|
| 395 |
+
|
| 396 |
+
with lower_to_next():
|
| 397 |
+
result = vmap_function(info, in_dims, *unwrapped_operands, **kwargs)
|
| 398 |
+
validate_vmap_returns_tuple_of_two_elements(result)
|
| 399 |
+
unwrapped_output, out_dims = result
|
| 400 |
+
|
| 401 |
+
# See NOTE [mark_dirty object identity check]
|
| 402 |
+
def wrap_fn(output: torch.Tensor, out_dim: int | None) -> torch.Tensor:
|
| 403 |
+
return (
|
| 404 |
+
output
|
| 405 |
+
if out_dim is None
|
| 406 |
+
else _add_batch_dim(output, out_dim, current_level)
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
return wrap_outputs_maintaining_identity(
|
| 410 |
+
unwrapped_output, unwrapped_operands, operands, wrap_fn, out_dims=out_dims
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def unpack_outputs(outputs: tuple[Any, ...]) -> tuple[Any, Any]:
|
| 415 |
+
out_dims = outputs[-1]
|
| 416 |
+
if isinstance(out_dims, tuple):
|
| 417 |
+
outputs = outputs[:-1]
|
| 418 |
+
else:
|
| 419 |
+
outputs = outputs[0]
|
| 420 |
+
return outputs, out_dims
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def custom_function_call_vmap_generate_rule(
|
| 424 |
+
interpreter: VmapInterpreter,
|
| 425 |
+
autograd_function: type[torch.autograd.Function],
|
| 426 |
+
*operands: Any,
|
| 427 |
+
) -> Any:
|
| 428 |
+
unwrapped_operands, in_dims = unwrap_batched(operands, interpreter.level())
|
| 429 |
+
vmapped_function = vmapify_autograd_function(
|
| 430 |
+
autograd_function,
|
| 431 |
+
in_dims,
|
| 432 |
+
interpreter.batch_size(),
|
| 433 |
+
interpreter.randomness(),
|
| 434 |
+
)
|
| 435 |
+
with interpreter.lower():
|
| 436 |
+
outputs = custom_function_call(vmapped_function, *unwrapped_operands)
|
| 437 |
+
|
| 438 |
+
if not isinstance(outputs, tuple):
|
| 439 |
+
raise AssertionError(f"expected outputs to be a tuple, got {type(outputs)}")
|
| 440 |
+
outputs, out_dims = unpack_outputs(outputs)
|
| 441 |
+
return wrap_batched(outputs, out_dims, interpreter.level())
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
@custom_function_call.py_impl(TransformType.Functionalize)
|
| 445 |
+
def custom_function_call_functionalize(
|
| 446 |
+
interpreter: FuncTorchInterpreter,
|
| 447 |
+
autograd_function: type[torch.autograd.Function],
|
| 448 |
+
generate_vmap_rule: bool,
|
| 449 |
+
*operands: Any,
|
| 450 |
+
) -> Any:
|
| 451 |
+
raise RuntimeError("NYI: Functionalize rule for custom_function_call")
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def vmapify_autograd_function(
|
| 455 |
+
autograd_function: type[torch.autograd.Function],
|
| 456 |
+
in_dims: Any,
|
| 457 |
+
batch_size: int,
|
| 458 |
+
randomness: str,
|
| 459 |
+
) -> type[torch.autograd.Function]:
|
| 460 |
+
def forward(*operands: Any) -> Any:
|
| 461 |
+
outputs, out_dims = restore_vmap(
|
| 462 |
+
autograd_function.forward, in_dims, batch_size, randomness
|
| 463 |
+
)(*operands)
|
| 464 |
+
if isinstance(outputs, torch.Tensor):
|
| 465 |
+
return outputs, out_dims
|
| 466 |
+
else:
|
| 467 |
+
return *outputs, out_dims
|
| 468 |
+
|
| 469 |
+
def setup_context(ctx: Any, inputs: Any, outputs: Any) -> None:
|
| 470 |
+
outputs, out_dims = unpack_outputs(outputs)
|
| 471 |
+
key = id(Generated)
|
| 472 |
+
|
| 473 |
+
def inner(inputs: Any, outputs: Any) -> None:
|
| 474 |
+
# wrapped_ctx.save_for_backward will:
|
| 475 |
+
# - unwrap batchedtensors into (tensor, bdim)
|
| 476 |
+
# - save_for_backward(*unwrapped_tensors)
|
| 477 |
+
# - assign the bdims to wrapped_ctx._pt_saved_tensors_bdims
|
| 478 |
+
wrapped_ctx = CtxCustomSave(ctx, current_level())
|
| 479 |
+
autograd_function.setup_context(wrapped_ctx, inputs, outputs)
|
| 480 |
+
|
| 481 |
+
# input_shapes are used for reductify later to reduce expanded gradients
|
| 482 |
+
# to the correct shape.
|
| 483 |
+
# See NOTE: [Why can't we rely on autograd to reduce expanded gradients?]
|
| 484 |
+
# for more details
|
| 485 |
+
input_shapes = tuple(
|
| 486 |
+
inp.shape if isinstance(inp, torch.Tensor) else None for inp in inputs
|
| 487 |
+
)
|
| 488 |
+
if not hasattr(ctx, "_pt_input_shapes"):
|
| 489 |
+
# pyrefly: ignore [implicit-any]
|
| 490 |
+
ctx._pt_input_shapes = {}
|
| 491 |
+
ctx._pt_input_shapes.update({key: input_shapes})
|
| 492 |
+
|
| 493 |
+
if not hasattr(ctx, "_pt_saved_tensors_bdims_stack"):
|
| 494 |
+
# pyrefly: ignore [implicit-any]
|
| 495 |
+
ctx._pt_saved_tensors_bdims_stack = {}
|
| 496 |
+
ctx._pt_saved_tensors_bdims_stack.update(
|
| 497 |
+
{key: (wrapped_ctx._pt_saved_tensors_bdims)}
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
# See NOTE: [Why do we need to run setup_context under a vmap?]
|
| 501 |
+
restore_vmap(
|
| 502 |
+
inner,
|
| 503 |
+
(in_dims, out_dims),
|
| 504 |
+
batch_size,
|
| 505 |
+
randomness,
|
| 506 |
+
)(inputs, outputs)
|
| 507 |
+
|
| 508 |
+
if not hasattr(ctx, "_pt_out_dims"):
|
| 509 |
+
# pyrefly: ignore [implicit-any]
|
| 510 |
+
ctx._pt_out_dims = {}
|
| 511 |
+
ctx._pt_out_dims.update({key: out_dims})
|
| 512 |
+
|
| 513 |
+
def jvp(ctx: Any, *tangents: Any) -> Any:
|
| 514 |
+
key = id(Generated)
|
| 515 |
+
|
| 516 |
+
def jvp_no_context(saved_tensors: Any, tangents: Any) -> Any:
|
| 517 |
+
wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors)
|
| 518 |
+
return autograd_function.jvp(wrapped_ctx, *tangents)
|
| 519 |
+
|
| 520 |
+
tangent_in_dims = get_tangents_in_dims(in_dims, tangents)
|
| 521 |
+
out_tangents, out_tangents_dims = restore_vmap(
|
| 522 |
+
jvp_no_context,
|
| 523 |
+
(ctx._pt_saved_tensors_bdims_stack[key], tangent_in_dims),
|
| 524 |
+
batch_size,
|
| 525 |
+
randomness,
|
| 526 |
+
)(ctx.saved_tensors, tangents)
|
| 527 |
+
|
| 528 |
+
result = reductify(
|
| 529 |
+
out_tangents, out_tangents_dims, ctx._pt_out_dims[key], batch_size
|
| 530 |
+
)
|
| 531 |
+
if isinstance(result, torch.Tensor):
|
| 532 |
+
return result, None
|
| 533 |
+
else:
|
| 534 |
+
return *result, None
|
| 535 |
+
|
| 536 |
+
def backward(ctx: Any, *grad_outputs: Any) -> Any:
|
| 537 |
+
key = id(Generated)
|
| 538 |
+
grad_outputs_ = grad_outputs[:-1]
|
| 539 |
+
grad_outputs_in_dims = ctx._pt_out_dims[key]
|
| 540 |
+
|
| 541 |
+
if not isinstance(grad_outputs_in_dims, tuple):
|
| 542 |
+
grad_outputs_in_dims = (grad_outputs_in_dims,)
|
| 543 |
+
|
| 544 |
+
grad_outputs_in_dims = tuple(
|
| 545 |
+
in_dim if grad_output is not None else None
|
| 546 |
+
for grad_output, in_dim in zip(grad_outputs_, grad_outputs_in_dims)
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
def backward_no_context(inputs: Any) -> Any:
|
| 550 |
+
saved_tensors, grad_outputs = inputs
|
| 551 |
+
wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors)
|
| 552 |
+
return autograd_function.backward(wrapped_ctx, *grad_outputs)
|
| 553 |
+
|
| 554 |
+
grad_ins, grad_ins_dims = restore_vmap(
|
| 555 |
+
backward_no_context,
|
| 556 |
+
((ctx._pt_saved_tensors_bdims_stack[key], grad_outputs_in_dims),),
|
| 557 |
+
batch_size,
|
| 558 |
+
randomness,
|
| 559 |
+
)((ctx.saved_tensors, grad_outputs_))
|
| 560 |
+
result = reductify(
|
| 561 |
+
grad_ins, grad_ins_dims, in_dims, batch_size, ctx._pt_input_shapes[key]
|
| 562 |
+
)
|
| 563 |
+
return result
|
| 564 |
+
|
| 565 |
+
name = f"Vmapped{autograd_function.__name__}"
|
| 566 |
+
Generated = type(
|
| 567 |
+
name,
|
| 568 |
+
(torch.autograd.Function,),
|
| 569 |
+
{
|
| 570 |
+
"forward": staticmethod(forward),
|
| 571 |
+
"backward": staticmethod(backward),
|
| 572 |
+
"jvp": staticmethod(jvp),
|
| 573 |
+
"setup_context": staticmethod(setup_context),
|
| 574 |
+
"generate_vmap_rule": True,
|
| 575 |
+
},
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
return Generated
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
# tangents might be None, so we need to replace
|
| 582 |
+
# the corresponding in_dims with None.
|
| 583 |
+
def get_tangents_in_dims(input_dims: Any, tangents: tuple[Any, ...]) -> Any:
|
| 584 |
+
flat_in_dims, spec = pytree.tree_flatten(input_dims)
|
| 585 |
+
flat_tangents = pytree.arg_tree_leaves(*tangents)
|
| 586 |
+
result = [
|
| 587 |
+
None if tangent is None else in_dim
|
| 588 |
+
for in_dim, tangent in zip(flat_in_dims, flat_tangents)
|
| 589 |
+
]
|
| 590 |
+
return pytree.tree_unflatten(result, spec)
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
# NOTE: [Why do we need to run setup_context under a vmap?]
|
| 594 |
+
# Consider the following autograd.Function
|
| 595 |
+
#
|
| 596 |
+
# class Sum(torch.autograd.Function):
|
| 597 |
+
# @staticmethod
|
| 598 |
+
# def forward(x):
|
| 599 |
+
# return x.sum()
|
| 600 |
+
# @staticmethod
|
| 601 |
+
# def setup_context(ctx, inputs, outputs):
|
| 602 |
+
# ctx.x_shape = inputs[0]
|
| 603 |
+
# @staticmethod
|
| 604 |
+
# def backward(ctx, gy):
|
| 605 |
+
# return gy.expand(ctx.x_shape)
|
| 606 |
+
#
|
| 607 |
+
# x = torch.randn(B, 4)
|
| 608 |
+
# in_dims = 0
|
| 609 |
+
# vmap(Sum.apply, in_dims)(x)
|
| 610 |
+
#
|
| 611 |
+
# Let's assume for a moment that we didn't vmap setup_context in VmappedSum:
|
| 612 |
+
#
|
| 613 |
+
# class VmappedSum(torch.autograd.Function):
|
| 614 |
+
# @staticmethod
|
| 615 |
+
# def forward(x):
|
| 616 |
+
# return vmap(Sum.forward, in_dims)(x)
|
| 617 |
+
#
|
| 618 |
+
# @staticmethod
|
| 619 |
+
# def setup_context(ctx, inputs, outputs):
|
| 620 |
+
# Sum.setup_context(ctx, inputs, outputs)
|
| 621 |
+
#
|
| 622 |
+
# @staticmethod
|
| 623 |
+
# def backward(ctx, gy):
|
| 624 |
+
# def backward_no_context(gy):
|
| 625 |
+
# return gy.expand(ctx.x_shape)
|
| 626 |
+
#
|
| 627 |
+
# dims = (0,)
|
| 628 |
+
# gx = vmap(backward_no_context, dims)(gy)
|
| 629 |
+
# return gx
|
| 630 |
+
#
|
| 631 |
+
# We end up saving [B, 4] as x_shape. In the backward, gy has shape [B],
|
| 632 |
+
# and we're doing:
|
| 633 |
+
#
|
| 634 |
+
# def backward_no_context(gy):
|
| 635 |
+
# return gy.expand([B, 4])
|
| 636 |
+
#
|
| 637 |
+
# gx = vmap(backward_no_context, dims)(gy: "Tensor[B]")
|
| 638 |
+
#
|
| 639 |
+
# This gives us the wrong result (gx has shape [B, B, 4], but it should
|
| 640 |
+
# have shape [4]). Performing vmap over setup_context means the shape
|
| 641 |
+
# saved has shape [4] and leads to a correct result shape for gx.
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
# Wraps a ctx object. Forwards all attr accesses to the underlying object
|
| 645 |
+
# except for the attrs in _pt_attrs
|
| 646 |
+
class WrappedCtx:
|
| 647 |
+
_pt_reserved_attrs: tuple[str, ...] = ("_pt_reserved_attrs", "_pt_inner_ctx")
|
| 648 |
+
|
| 649 |
+
def __init__(self, ctx: Any) -> None:
|
| 650 |
+
if not isinstance(ctx, WrappedCtx):
|
| 651 |
+
reserved_attrs = type(self)._pt_reserved_attrs
|
| 652 |
+
for name in reserved_attrs:
|
| 653 |
+
if not hasattr(ctx, name):
|
| 654 |
+
continue
|
| 655 |
+
raise RuntimeError(
|
| 656 |
+
f"PyTorch reserves the {reserved_attrs} field on ctx. "
|
| 657 |
+
"Please name your fields on ctx something else to avoid name "
|
| 658 |
+
"collision."
|
| 659 |
+
)
|
| 660 |
+
self._pt_inner_ctx = ctx
|
| 661 |
+
|
| 662 |
+
def __getattr__(self, name: str) -> Any:
|
| 663 |
+
return getattr(self._pt_inner_ctx, name)
|
| 664 |
+
|
| 665 |
+
def __setattr__(self, name: str, value: Any) -> None:
|
| 666 |
+
if name in type(self)._pt_reserved_attrs:
|
| 667 |
+
self.__dict__[name] = value
|
| 668 |
+
return
|
| 669 |
+
return setattr(self._pt_inner_ctx, name, value)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
# Wraps ctx to create a new ctx object that overrides saved_tensors.
|
| 673 |
+
class CtxWithSavedTensors(WrappedCtx):
|
| 674 |
+
_pt_reserved_attrs = ("_pt_new_saved_tensors", *WrappedCtx._pt_reserved_attrs)
|
| 675 |
+
|
| 676 |
+
def __init__(self, ctx: Any, new_saved_tensors: Sequence[torch.Tensor]) -> None:
|
| 677 |
+
super().__init__(ctx)
|
| 678 |
+
self._pt_new_saved_tensors = new_saved_tensors
|
| 679 |
+
|
| 680 |
+
@property
|
| 681 |
+
def saved_tensors(self) -> Sequence[torch.Tensor]:
|
| 682 |
+
return self._pt_new_saved_tensors
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
class CtxCustomSave(WrappedCtx):
|
| 686 |
+
_pt_reserved_attrs = (
|
| 687 |
+
"_pt_saved_tensors_bdims",
|
| 688 |
+
"_pt_current_level",
|
| 689 |
+
*WrappedCtx._pt_reserved_attrs,
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
def __init__(self, ctx: Any, current_level: int) -> None:
|
| 693 |
+
super().__init__(ctx)
|
| 694 |
+
self._pt_saved_tensors_bdims: tuple[Any, ...] = ()
|
| 695 |
+
self._pt_current_level = current_level
|
| 696 |
+
|
| 697 |
+
def save_for_backward(self, *tensors: torch.Tensor) -> None:
|
| 698 |
+
unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level)
|
| 699 |
+
self._pt_inner_ctx.save_for_backward(*unwrapped_tensors)
|
| 700 |
+
self._pt_saved_tensors_bdims = bdims
|
| 701 |
+
|
| 702 |
+
def save_for_forward(self, *tensors: torch.Tensor) -> None:
|
| 703 |
+
unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level)
|
| 704 |
+
self._pt_inner_ctx.save_for_forward(*unwrapped_tensors)
|
| 705 |
+
self._pt_saved_tensors_bdims = bdims
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
def reductify(
|
| 709 |
+
grad_input: torch.Tensor | tuple[torch.Tensor, ...],
|
| 710 |
+
grad_input_bdim: int | tuple[int, ...],
|
| 711 |
+
input_bdim: int | tuple[int, ...],
|
| 712 |
+
batch_size: int,
|
| 713 |
+
target_shape_without_bdim_to_reduce_to: Any = None,
|
| 714 |
+
) -> tuple[Any, ...]:
|
| 715 |
+
if not isinstance(grad_input, tuple):
|
| 716 |
+
grad_input = (grad_input,)
|
| 717 |
+
if not isinstance(grad_input_bdim, tuple):
|
| 718 |
+
grad_input_bdim = (grad_input_bdim,)
|
| 719 |
+
if not isinstance(input_bdim, tuple):
|
| 720 |
+
input_bdim = (input_bdim,)
|
| 721 |
+
|
| 722 |
+
if target_shape_without_bdim_to_reduce_to is None:
|
| 723 |
+
target_shape_without_bdim_to_reduce_to = len(grad_input) * (None,)
|
| 724 |
+
result = tuple(
|
| 725 |
+
reductify_leaf(gi, gi_bdim, i_bdim, batch_size, maybe_ishape)
|
| 726 |
+
for gi, gi_bdim, i_bdim, maybe_ishape in zip(
|
| 727 |
+
grad_input,
|
| 728 |
+
grad_input_bdim,
|
| 729 |
+
input_bdim,
|
| 730 |
+
target_shape_without_bdim_to_reduce_to,
|
| 731 |
+
)
|
| 732 |
+
)
|
| 733 |
+
return result
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def reductify_leaf(
|
| 737 |
+
grad_input: torch.Tensor | None,
|
| 738 |
+
grad_input_bdim: int | None,
|
| 739 |
+
input_bdim: int | None,
|
| 740 |
+
batch_size: int,
|
| 741 |
+
target_shape_without_bdim_to_reduce_to: Any = None,
|
| 742 |
+
) -> torch.Tensor | None:
|
| 743 |
+
if grad_input is None:
|
| 744 |
+
return None
|
| 745 |
+
|
| 746 |
+
if grad_input_bdim is None and input_bdim is None:
|
| 747 |
+
return grad_input
|
| 748 |
+
|
| 749 |
+
if grad_input_bdim is not None and input_bdim is None:
|
| 750 |
+
return grad_input.sum(grad_input_bdim)
|
| 751 |
+
|
| 752 |
+
# NOTE: [Why can't we rely on autograd to reduce expanded gradients?]
|
| 753 |
+
# For reverse-mode AD,
|
| 754 |
+
# given a grad_input and input, it is valid for the user to return a
|
| 755 |
+
# grad_input that has a broadcasted shape when compared to the input.
|
| 756 |
+
# In this situation, autograd automatically reduces the grad_input to
|
| 757 |
+
# the shape of the input.
|
| 758 |
+
#
|
| 759 |
+
# However, when input_bdim is not None, we have problems.
|
| 760 |
+
#
|
| 761 |
+
# [example 1]
|
| 762 |
+
# grad_input: Tensor[3, 4], input: Tensor[B, 4]
|
| 763 |
+
# We can expand grad_input to Tensor[B, 3, 4], but that isn't broadcastable
|
| 764 |
+
# from [B, 4].
|
| 765 |
+
#
|
| 766 |
+
# [example 2]
|
| 767 |
+
# grad_input: Tensor[3, B, 4], input: Tensor[B, 4]
|
| 768 |
+
# We can swizzle grad_input to Tensor[B, 3, 4], but that isn't broadcastable
|
| 769 |
+
# from [B, 4].
|
| 770 |
+
#
|
| 771 |
+
# This means that we need to also reduce the grad_input to the shape of the
|
| 772 |
+
# input. This behavior is controlled by the `target_shape_without_bdim_to_reduce_to` flag;
|
| 773 |
+
# if not-None then we do the reducing manually, otherwise, we do not do a reduction.
|
| 774 |
+
if input_bdim is None:
|
| 775 |
+
raise AssertionError("input_bdim must not be None")
|
| 776 |
+
|
| 777 |
+
if grad_input_bdim is None:
|
| 778 |
+
grad_input = grad_input.unsqueeze(input_bdim)
|
| 779 |
+
new_shape = list(grad_input.shape)
|
| 780 |
+
new_shape[input_bdim] = batch_size
|
| 781 |
+
grad_input = grad_input.expand(new_shape)
|
| 782 |
+
grad_input_bdim = input_bdim
|
| 783 |
+
|
| 784 |
+
if target_shape_without_bdim_to_reduce_to is not None:
|
| 785 |
+
return vmap(
|
| 786 |
+
torch.Tensor.sum_to_size,
|
| 787 |
+
in_dims=(grad_input_bdim, None),
|
| 788 |
+
out_dims=input_bdim,
|
| 789 |
+
)(grad_input, target_shape_without_bdim_to_reduce_to)
|
| 790 |
+
|
| 791 |
+
if input_bdim != grad_input_bdim:
|
| 792 |
+
grad_input = grad_input.movedim(grad_input_bdim, input_bdim)
|
| 793 |
+
return grad_input
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
def autograd_function_forward_rewritten(
|
| 797 |
+
original_forward: Callable[_P, _R],
|
| 798 |
+
original_setup_context: Callable[..., Any],
|
| 799 |
+
) -> Callable[..., _R]:
|
| 800 |
+
def new_forward(ctx: Any, *args: _P.args, **kwargs: _P.kwargs) -> _R:
|
| 801 |
+
output = original_forward(*args, **kwargs)
|
| 802 |
+
original_setup_context(ctx, args, output)
|
| 803 |
+
return output
|
| 804 |
+
|
| 805 |
+
return new_forward
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
class AutogradFunctionApply(HigherOrderOperator):
|
| 809 |
+
def __init__(self) -> None:
|
| 810 |
+
super().__init__("autograd_function_apply")
|
| 811 |
+
|
| 812 |
+
def __call__(
|
| 813 |
+
self,
|
| 814 |
+
fwd: torch.fx.GraphModule,
|
| 815 |
+
bwd: torch.fx.GraphModule,
|
| 816 |
+
*fwd_args: Any,
|
| 817 |
+
**fwd_kwargs: Any,
|
| 818 |
+
) -> Any:
|
| 819 |
+
saved_values: Iterable[Any] | None = None
|
| 820 |
+
non_differentiable_idx = fwd_kwargs["non_differentiable_idx"]
|
| 821 |
+
saved_for_backward_idx = fwd_kwargs["saved_for_backward_idx"]
|
| 822 |
+
|
| 823 |
+
class ApplyTemplate(torch.autograd.Function):
|
| 824 |
+
@staticmethod
|
| 825 |
+
def forward(*args: Any, **kwargs: Any) -> Any:
|
| 826 |
+
nonlocal saved_values
|
| 827 |
+
|
| 828 |
+
# The Interpreter here is required to propagate metadata
|
| 829 |
+
# from the dynamo graph body to the local_map graph body.
|
| 830 |
+
# This is required for fx_traceback.annotate for work.
|
| 831 |
+
output, saved_values = torch.fx.Interpreter(fwd).run(*args)
|
| 832 |
+
|
| 833 |
+
# See Note [Activations with no version counter checks in eager]
|
| 834 |
+
# Mark tensors that came from ctx.save_for_backward with metadata.
|
| 835 |
+
# This allows AOT autograd to distinguish between tensors saved via
|
| 836 |
+
# save_for_backward vs those stashed directly on ctx (e.g., ctx.x = x).
|
| 837 |
+
from torch.fx.experimental.proxy_tensor import _get_proxies
|
| 838 |
+
|
| 839 |
+
for idx, t in enumerate(saved_values):
|
| 840 |
+
if idx not in saved_for_backward_idx:
|
| 841 |
+
for proxy in _get_proxies(t):
|
| 842 |
+
proxy.node.meta["saved_tensor_with_no_vc_check"] = True
|
| 843 |
+
|
| 844 |
+
return output
|
| 845 |
+
|
| 846 |
+
@staticmethod
|
| 847 |
+
def setup_context(ctx: Any, inputs: tuple[Any, ...], output: Any) -> None:
|
| 848 |
+
# If users call ctx.mark_non_differentiable() in the original fwd function.
|
| 849 |
+
if len(non_differentiable_idx) > 0:
|
| 850 |
+
non_differentiable_output = []
|
| 851 |
+
for i, x in enumerate(output):
|
| 852 |
+
if i in non_differentiable_idx:
|
| 853 |
+
non_differentiable_output.append(x)
|
| 854 |
+
ctx.mark_non_differentiable(*non_differentiable_output)
|
| 855 |
+
|
| 856 |
+
@staticmethod
|
| 857 |
+
def backward(ctx: Any, *grad: Any) -> Any:
|
| 858 |
+
# The Interpreter here is required to propagate metadata
|
| 859 |
+
# from the dynamo graph body to the local_map graph body.
|
| 860 |
+
# This is required for fx_traceback.annotate for work.
|
| 861 |
+
|
| 862 |
+
if saved_values is None:
|
| 863 |
+
raise AssertionError("saved_values must not be None")
|
| 864 |
+
return torch.fx.Interpreter(bwd).run(*grad, *saved_values)
|
| 865 |
+
|
| 866 |
+
return ApplyTemplate.apply(*fwd_args)
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
autograd_function_apply = AutogradFunctionApply()
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
class DynamoAutogradFunctionTraceHelper:
|
| 873 |
+
@staticmethod
|
| 874 |
+
def fwd_trace_helper(orig_fwd: Callable[_P, Any]) -> Callable[_P, Any]:
|
| 875 |
+
# autograd.Function forward does more than just running the forward method. Most
|
| 876 |
+
# of this logic is in C++. Here, we rewrite that functionality in python and let
|
| 877 |
+
# Dynamo trace it.
|
| 878 |
+
def inner(*args: _P.args, **kwargs: _P.kwargs) -> Any:
|
| 879 |
+
with torch.no_grad():
|
| 880 |
+
outs = orig_fwd(*args, **kwargs)
|
| 881 |
+
|
| 882 |
+
# Handle the case where if the input is passed on directly to the output, we call view_as
|
| 883 |
+
# Refer to https://github.com/pytorch/pytorch/blob/main/torch/csrc/autograd/custom_function.cpp#L254
|
| 884 |
+
tensor_args = {arg for arg in args if isinstance(arg, torch.Tensor)}
|
| 885 |
+
if isinstance(outs, torch.Tensor):
|
| 886 |
+
if outs in tensor_args:
|
| 887 |
+
return outs.view_as(outs)
|
| 888 |
+
else:
|
| 889 |
+
return outs
|
| 890 |
+
|
| 891 |
+
new_outs = []
|
| 892 |
+
for out in outs:
|
| 893 |
+
if isinstance(out, torch.Tensor):
|
| 894 |
+
if out in tensor_args:
|
| 895 |
+
new_outs.append(out.view_as(out))
|
| 896 |
+
else:
|
| 897 |
+
new_outs.append(out)
|
| 898 |
+
else:
|
| 899 |
+
new_outs.append(out)
|
| 900 |
+
return tuple(new_outs)
|
| 901 |
+
|
| 902 |
+
# TODO - there is missing functionality here, where
|
| 903 |
+
# autograd.Function overwrites the requires_grad_ of the output
|
| 904 |
+
# tensors depending on the `mark_non_differentiable`. Currently,
|
| 905 |
+
# this is handled hackily in Dynamo, where we just overwrite the
|
| 906 |
+
# variable trackers requires_grad. Refer to the function -
|
| 907 |
+
# overwrite_tensor_vt_requires_grad
|
| 908 |
+
|
| 909 |
+
return inner
|
venv/lib/python3.14/site-packages/torch/_functorch/batch_norm_replacement.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
from torch._functorch.utils import exposed_in
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def batch_norm_without_running_stats(module: nn.Module) -> None:
|
| 6 |
+
if (
|
| 7 |
+
isinstance(module, nn.modules.batchnorm._BatchNorm)
|
| 8 |
+
and module.track_running_stats
|
| 9 |
+
):
|
| 10 |
+
module.running_mean = None
|
| 11 |
+
module.running_var = None
|
| 12 |
+
module.num_batches_tracked = None
|
| 13 |
+
module.track_running_stats = False
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@exposed_in("torch.func")
|
| 17 |
+
def replace_all_batch_norm_modules_(root: nn.Module) -> nn.Module:
|
| 18 |
+
"""
|
| 19 |
+
In place updates :attr:`root` by setting the ``running_mean`` and ``running_var`` to be None and
|
| 20 |
+
setting track_running_stats to be False for any nn.BatchNorm module in :attr:`root`
|
| 21 |
+
"""
|
| 22 |
+
# base case
|
| 23 |
+
batch_norm_without_running_stats(root)
|
| 24 |
+
|
| 25 |
+
for obj in root.modules():
|
| 26 |
+
batch_norm_without_running_stats(obj)
|
| 27 |
+
return root
|
venv/lib/python3.14/site-packages/torch/_functorch/benchmark_utils.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import json
|
| 5 |
+
import operator
|
| 6 |
+
import os
|
| 7 |
+
import time
|
| 8 |
+
from contextlib import AbstractContextManager
|
| 9 |
+
from typing import Any, TYPE_CHECKING
|
| 10 |
+
from typing_extensions import TypeVar
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch.profiler import profile, ProfilerActivity
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from collections.abc import Callable, Sequence
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_R = TypeVar("_R")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def synchronize() -> None:
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def dump_chrome_trace(
|
| 28 |
+
f: Callable[[tuple[Any, ...]], _R],
|
| 29 |
+
input_: tuple[Any, ...],
|
| 30 |
+
trace_filename: str,
|
| 31 |
+
optimize_ctx: AbstractContextManager[Any],
|
| 32 |
+
activities: Sequence[ProfilerActivity],
|
| 33 |
+
num_runs: int = 1,
|
| 34 |
+
devices: list[str] | None = None,
|
| 35 |
+
kwargs_for_f: dict[str, Any] | None = None,
|
| 36 |
+
kwargs_for_profiler: dict[str, Any] | None = None,
|
| 37 |
+
) -> float:
|
| 38 |
+
"""
|
| 39 |
+
Output the chrome trace of running f(input_, **kwargs_for_f) with [optimize_ctx]
|
| 40 |
+
[num_runs] times to [trace_filename].
|
| 41 |
+
|
| 42 |
+
[activities] are the activities that the profiler will record, e.g. ProfilerActivity.CUDA.
|
| 43 |
+
Return total runtime without the profiler
|
| 44 |
+
|
| 45 |
+
Outputs to trace_filename
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
if devices is None:
|
| 49 |
+
devices = ["cuda"]
|
| 50 |
+
|
| 51 |
+
global synchronize
|
| 52 |
+
if devices != ["cpu"] and torch.cuda.is_available():
|
| 53 |
+
synchronize = torch.cuda.synchronize
|
| 54 |
+
|
| 55 |
+
if kwargs_for_f is None:
|
| 56 |
+
kwargs_for_f = {}
|
| 57 |
+
if kwargs_for_profiler is None:
|
| 58 |
+
kwargs_for_profiler = {}
|
| 59 |
+
|
| 60 |
+
with optimize_ctx:
|
| 61 |
+
torch.manual_seed(1337)
|
| 62 |
+
for _ in range(5): # warmup runs
|
| 63 |
+
f(input_, **kwargs_for_f)
|
| 64 |
+
synchronize()
|
| 65 |
+
torch.manual_seed(1337)
|
| 66 |
+
t0 = time.perf_counter()
|
| 67 |
+
for _ in range(num_runs):
|
| 68 |
+
f(input_, **kwargs_for_f)
|
| 69 |
+
synchronize()
|
| 70 |
+
t1 = time.perf_counter()
|
| 71 |
+
timing = t1 - t0
|
| 72 |
+
|
| 73 |
+
with profile(activities=activities, **kwargs_for_profiler) as prof:
|
| 74 |
+
with optimize_ctx:
|
| 75 |
+
synchronize()
|
| 76 |
+
torch.manual_seed(1337)
|
| 77 |
+
for _ in range(num_runs):
|
| 78 |
+
f(input_, **kwargs_for_f)
|
| 79 |
+
synchronize()
|
| 80 |
+
prof.export_chrome_trace(trace_filename)
|
| 81 |
+
|
| 82 |
+
return timing
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def get_chrome_trace_events(filename: str) -> list[dict[str, Any]]:
|
| 86 |
+
with open(filename) as f:
|
| 87 |
+
data = json.load(f)
|
| 88 |
+
events = data["traceEvents"]
|
| 89 |
+
return events
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def is_gpu_compute_event(event: dict[str, Any]) -> bool:
|
| 93 |
+
global gpu_pids
|
| 94 |
+
return (
|
| 95 |
+
"pid" in event
|
| 96 |
+
and event["pid"] in gpu_pids
|
| 97 |
+
and "ph" in event
|
| 98 |
+
and event["ph"] == "X"
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def get_sorted_gpu_events(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 103 |
+
sorted_gpu_events: list[dict[str, Any]] = []
|
| 104 |
+
for event in events:
|
| 105 |
+
if not is_gpu_compute_event(event):
|
| 106 |
+
continue
|
| 107 |
+
sorted_gpu_events.append(event)
|
| 108 |
+
return sorted(sorted_gpu_events, key=operator.itemgetter("ts"))
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def get_duration(sorted_gpu_events: list[dict[str, Any]]) -> int:
|
| 112 |
+
if len(sorted_gpu_events) == 0:
|
| 113 |
+
return 0
|
| 114 |
+
event = sorted_gpu_events[0]
|
| 115 |
+
current_end_time = event["ts"] + event["dur"]
|
| 116 |
+
total_duration = event["dur"]
|
| 117 |
+
for event in sorted_gpu_events[1:]:
|
| 118 |
+
start_time = max(event["ts"], current_end_time)
|
| 119 |
+
end_time = event["ts"] + event["dur"]
|
| 120 |
+
total_duration = total_duration + max(end_time - start_time, 0)
|
| 121 |
+
current_end_time = max(current_end_time, end_time)
|
| 122 |
+
return total_duration
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def get_sorted_gpu_mm_conv_events(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 126 |
+
def is_mm_conv_event(event: dict[str, Any]) -> bool:
|
| 127 |
+
return "name" in event and (
|
| 128 |
+
"gemm" in event["name"]
|
| 129 |
+
or "conv" in event["name"]
|
| 130 |
+
or "cutlass" in event["name"]
|
| 131 |
+
or "wgrad" in event["name"]
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
gpu_events = get_sorted_gpu_events(events)
|
| 135 |
+
sorted_events: list[dict[str, Any]] = []
|
| 136 |
+
for event in gpu_events:
|
| 137 |
+
if not is_mm_conv_event(event):
|
| 138 |
+
continue
|
| 139 |
+
sorted_events.append(event)
|
| 140 |
+
return sorted_events
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
gpu_pids: list[Any] = []
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def compute_utilization(filename: str, total_length: float) -> tuple[float, float]:
|
| 147 |
+
"""
|
| 148 |
+
Process the chrome traces outputs by the pytorch profiler to compute GPU Utilization
|
| 149 |
+
and percent of times spent on matmul and convolution
|
| 150 |
+
|
| 151 |
+
Args:
|
| 152 |
+
filename(str): Name of chrome traces file produced by pytorch profiler
|
| 153 |
+
|
| 154 |
+
total_length(float): total length of the process without profiler in second
|
| 155 |
+
|
| 156 |
+
Return:
|
| 157 |
+
tuple: (GPU Utilization, percent of time spent on matmul and convolution)
|
| 158 |
+
"""
|
| 159 |
+
events = get_chrome_trace_events(filename)
|
| 160 |
+
|
| 161 |
+
# get pids of GPU events
|
| 162 |
+
global gpu_pids
|
| 163 |
+
gpu_pids = []
|
| 164 |
+
for event in events:
|
| 165 |
+
if "name" not in event:
|
| 166 |
+
continue
|
| 167 |
+
if event["name"] == "process_labels" and "GPU" in event["args"]["labels"]:
|
| 168 |
+
gpu_pids.append(event["pid"])
|
| 169 |
+
|
| 170 |
+
total_length = total_length * 1e6
|
| 171 |
+
sorted_gpu_events = get_sorted_gpu_events(events)
|
| 172 |
+
utilization = get_duration(sorted_gpu_events) / total_length
|
| 173 |
+
|
| 174 |
+
sorted_gpu_mm_conv_events = get_sorted_gpu_mm_conv_events(events)
|
| 175 |
+
mm_conv_utilization = get_duration(sorted_gpu_mm_conv_events) / total_length
|
| 176 |
+
|
| 177 |
+
return utilization, mm_conv_utilization
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def benchmark_utilization(
|
| 181 |
+
f: Callable[[tuple[Any, ...]], _R],
|
| 182 |
+
input_: tuple[Any, ...],
|
| 183 |
+
trace_folder: str,
|
| 184 |
+
optimize_ctx: AbstractContextManager[Any] | None = None,
|
| 185 |
+
trace_file_name: str = "tmp_chrome_trace",
|
| 186 |
+
num_runs: int = 1,
|
| 187 |
+
) -> tuple[float, float]:
|
| 188 |
+
"""
|
| 189 |
+
Benchmark the GPU Utilization and percent of time spent on matmul and convolution operations of
|
| 190 |
+
running f(input_, **kwargs_for_f) with [optimize_ctx] [num_runs] times.
|
| 191 |
+
It will produce a chrome trace file in trace_folder/trace_file_name.json
|
| 192 |
+
|
| 193 |
+
Example:
|
| 194 |
+
|
| 195 |
+
```
|
| 196 |
+
def f(a):
|
| 197 |
+
return a.sum()
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
a = torch.rand(2**20, device="cuda")
|
| 201 |
+
utilization, mm_conv_utilization = benchmark_utilization(
|
| 202 |
+
f, a, "tmp", trace_file_name="tmp_chrome_trace"
|
| 203 |
+
)
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
f: function to benchmark
|
| 208 |
+
|
| 209 |
+
input_: input to :attr:`f`
|
| 210 |
+
|
| 211 |
+
trace_folder: name of the folder to store the chrome trace
|
| 212 |
+
|
| 213 |
+
optimize_ctx: the context in which f will run
|
| 214 |
+
|
| 215 |
+
trace_file_name: name of the dumped chrome trace file, default to "tmp_chrome_trace"
|
| 216 |
+
|
| 217 |
+
num_runs: number of times to run f, excluding the warm-up runs, default to 1.
|
| 218 |
+
|
| 219 |
+
Return:
|
| 220 |
+
tuple: (GPU Utilization, percent of time spent on matmul and convolution)
|
| 221 |
+
|
| 222 |
+
"""
|
| 223 |
+
isExist = os.path.exists(trace_folder)
|
| 224 |
+
if not isExist:
|
| 225 |
+
os.makedirs(trace_folder)
|
| 226 |
+
print("create folder " + trace_folder)
|
| 227 |
+
|
| 228 |
+
if optimize_ctx is None:
|
| 229 |
+
optimize_ctx = contextlib.nullcontext()
|
| 230 |
+
|
| 231 |
+
chrome_trace_file_name = os.path.join(trace_folder, trace_file_name + ".json")
|
| 232 |
+
total_length = dump_chrome_trace(
|
| 233 |
+
f,
|
| 234 |
+
input_,
|
| 235 |
+
chrome_trace_file_name,
|
| 236 |
+
optimize_ctx,
|
| 237 |
+
[ProfilerActivity.CUDA],
|
| 238 |
+
num_runs=num_runs,
|
| 239 |
+
devices=["cuda"],
|
| 240 |
+
)
|
| 241 |
+
utilization, mm_conv_utilization = compute_utilization(
|
| 242 |
+
chrome_trace_file_name, total_length
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
return utilization, mm_conv_utilization
|
venv/lib/python3.14/site-packages/torch/_functorch/compile_utils.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import operator
|
| 4 |
+
from typing import Any, TYPE_CHECKING
|
| 5 |
+
|
| 6 |
+
import sympy
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.fx as fx
|
| 10 |
+
from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
|
| 11 |
+
from torch.multiprocessing.reductions import StorageWeakRef
|
| 12 |
+
from torch.utils import _pytree as pytree
|
| 13 |
+
from torch.utils._pytree import tree_flatten
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from collections.abc import Callable
|
| 18 |
+
|
| 19 |
+
from torch._ops import OpOverloadPacket
|
| 20 |
+
from torch.utils._pytree import TreeSpec
|
| 21 |
+
|
| 22 |
+
aten = torch.ops.aten
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_aten_target(node: fx.Node) -> OpOverloadPacket | Callable[..., Any] | str:
|
| 26 |
+
if hasattr(node.target, "overloadpacket"):
|
| 27 |
+
return node.target.overloadpacket
|
| 28 |
+
return node.target
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
rand_ops = [
|
| 32 |
+
aten.dropout,
|
| 33 |
+
aten._fused_dropout,
|
| 34 |
+
aten._standard_gamma,
|
| 35 |
+
aten.bernoulli,
|
| 36 |
+
aten.multinomial,
|
| 37 |
+
aten.native_dropout,
|
| 38 |
+
aten.normal,
|
| 39 |
+
aten.poisson,
|
| 40 |
+
aten.binomial,
|
| 41 |
+
aten.rrelu,
|
| 42 |
+
aten.rand_like,
|
| 43 |
+
aten.rand,
|
| 44 |
+
aten.randint,
|
| 45 |
+
aten.randn,
|
| 46 |
+
aten.randperm,
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# return a new copy of torch.fx.graph.Graph with CSE applied to the input graph
|
| 51 |
+
def fx_graph_cse(fx_g: torch.fx.graph.Graph) -> fx.Graph:
|
| 52 |
+
new_graph = fx.Graph()
|
| 53 |
+
env: dict[
|
| 54 |
+
fx.Node, fx.Node
|
| 55 |
+
] = {} # map from node in the old graph to node in the new graph
|
| 56 |
+
hash_env: dict[
|
| 57 |
+
tuple[str, int], fx.Node
|
| 58 |
+
] = {} # map from hash to a node in the new graph
|
| 59 |
+
token_map: dict[tuple[str, int], dict[str, Any]] = {} # map from hash to token
|
| 60 |
+
|
| 61 |
+
from torch._inductor.pattern_matcher import (
|
| 62 |
+
compute_mutation_region_ids,
|
| 63 |
+
same_mutation_regions,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
compute_mutation_region_ids(fx_g) # type: ignore[arg-type]
|
| 67 |
+
|
| 68 |
+
# Make a set of separate storages returned from the output, which will be preserved
|
| 69 |
+
# when pruning. This prevents us from deduplicating returned tensors which have
|
| 70 |
+
# experienced identical operations, but are separate data structures in eager mode.
|
| 71 |
+
output_node: fx.Node = list(fx_g.nodes)[-1]
|
| 72 |
+
if output_node.op != "output":
|
| 73 |
+
raise AssertionError(
|
| 74 |
+
f"expected output_node.op to be 'output', got '{output_node.op}'"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
def checkable_node(node: fx.Node) -> bool:
|
| 78 |
+
"""We can evaluate only nodes that represent tensors with defined storage."""
|
| 79 |
+
if "val" not in node.meta or not isinstance(node.meta["val"], torch.Tensor):
|
| 80 |
+
return False
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
node.meta["val"].untyped_storage()
|
| 84 |
+
except NotImplementedError:
|
| 85 |
+
return False
|
| 86 |
+
|
| 87 |
+
return True
|
| 88 |
+
|
| 89 |
+
output_storages = {
|
| 90 |
+
StorageWeakRef(n.meta["val"].untyped_storage())
|
| 91 |
+
for n in output_node.all_input_nodes
|
| 92 |
+
if checkable_node(n)
|
| 93 |
+
}
|
| 94 |
+
nodes_that_alias_outputs = {
|
| 95 |
+
n
|
| 96 |
+
for n in fx_g.nodes
|
| 97 |
+
if checkable_node(n)
|
| 98 |
+
and StorageWeakRef(n.meta["val"].untyped_storage()) in output_storages
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
for n in fx_g.nodes:
|
| 102 |
+
# The placeholder, output, and get_attr nodes are copied to the new graph without change
|
| 103 |
+
# do not CSE away random operations
|
| 104 |
+
if (
|
| 105 |
+
n.op == "placeholder"
|
| 106 |
+
or n.op == "output"
|
| 107 |
+
or n.op == "get_attr"
|
| 108 |
+
or get_aten_target(n) in rand_ops
|
| 109 |
+
# aten.empty is non-deterministic, so don't CSE it.
|
| 110 |
+
# Also, aten.empty is almost always fusible into its consumer,
|
| 111 |
+
# so it's not worth CSEing.
|
| 112 |
+
or get_aten_target(n) is aten.empty
|
| 113 |
+
or n in nodes_that_alias_outputs
|
| 114 |
+
# This CSE pass currently doesn't handle re-propagation of unbacked
|
| 115 |
+
# meta where it'll sometimes eliminate a _local_scalar_dense but not
|
| 116 |
+
# replace the meta of downstream users. eg. one bug we've seen is:
|
| 117 |
+
#
|
| 118 |
+
# _local_scalar_dense_11: "Sym(u14)" = torch.ops.aten._local_scalar_dense.default(select_10);
|
| 119 |
+
# sym_sum_2: "Sym(u19 + u20 + u21)" = torch.sym_sum((_local_scalar_dense_11, _local_scalar_dense_12, _local_scalar_dense_13)) # noqa: B950
|
| 120 |
+
#
|
| 121 |
+
# Notice how _local_scalar_dense_11 is u14 but sym_sum_2's meta is incorrectly the old
|
| 122 |
+
# pre-cse value of u19.
|
| 123 |
+
or (
|
| 124 |
+
"val" in n.meta
|
| 125 |
+
and isinstance(n.meta["val"], sympy.Symbol)
|
| 126 |
+
and free_unbacked_symbols(n.meta["val"])
|
| 127 |
+
)
|
| 128 |
+
):
|
| 129 |
+
new_node = new_graph.node_copy(n, lambda x: env[x])
|
| 130 |
+
env[n] = new_node
|
| 131 |
+
else: # n.op == 'call_function', should never see n.op == 'call_module' or 'call_method'
|
| 132 |
+
# substitute args and kwargs members to their mapping in env if exists
|
| 133 |
+
# specs can be used to reconstruct nested list/dictionaries
|
| 134 |
+
def substitute(
|
| 135 |
+
arg_list: list[Any] | tuple[Any, ...],
|
| 136 |
+
) -> tuple[tuple[Any, ...], TreeSpec]:
|
| 137 |
+
arg_list, spec = tree_flatten(arg_list)
|
| 138 |
+
for i in range(len(arg_list)):
|
| 139 |
+
v = arg_list[i]
|
| 140 |
+
if isinstance(v, torch.fx.node.Node) and v in env:
|
| 141 |
+
arg_list[i] = env[v]
|
| 142 |
+
if isinstance(v, (torch.SymBool, torch.SymInt, torch.SymFloat)):
|
| 143 |
+
arg_list[i] = v.node
|
| 144 |
+
return tuple(arg_list), spec
|
| 145 |
+
|
| 146 |
+
args, args_spec = substitute(n.args)
|
| 147 |
+
kwargs, kwargs_spec = substitute(n.kwargs)
|
| 148 |
+
|
| 149 |
+
# each token corresponds to a unique node
|
| 150 |
+
# nodes with the same token can be substituted
|
| 151 |
+
token = {
|
| 152 |
+
"target": n.target,
|
| 153 |
+
"args": args,
|
| 154 |
+
"args_spec": args_spec,
|
| 155 |
+
"kwargs": kwargs,
|
| 156 |
+
"kwargs_spec": kwargs_spec,
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
# hash substituted args to a number, do not hash specs because specs are not hashable
|
| 160 |
+
# We need to add type into hash to avoid situations like:
|
| 161 |
+
# hash((primals_2, 1.0)) == hash((primals_2, 1))
|
| 162 |
+
hash_arg = hash(
|
| 163 |
+
(tuple((a, type(a)) for a in args), tuple((a, type(a)) for a in kwargs))
|
| 164 |
+
)
|
| 165 |
+
hash_val = (n.target, hash_arg)
|
| 166 |
+
|
| 167 |
+
# check if a node has a substitute and can be eliminated
|
| 168 |
+
hash_val_in_hash_env = hash_val in hash_env
|
| 169 |
+
overwrite_due_to_mutation = False
|
| 170 |
+
if hash_val_in_hash_env and token_map[hash_val] == token:
|
| 171 |
+
duplicate_n_prev = hash_env[hash_val]
|
| 172 |
+
if same_mutation_regions(n, duplicate_n_prev):
|
| 173 |
+
env[n] = duplicate_n_prev
|
| 174 |
+
continue
|
| 175 |
+
else:
|
| 176 |
+
# any futures duplicates should replace with n, not duplicate_n_prev
|
| 177 |
+
overwrite_due_to_mutation = True
|
| 178 |
+
|
| 179 |
+
new_node = new_graph.node_copy(n, lambda x: env[x])
|
| 180 |
+
env[n] = new_node
|
| 181 |
+
if overwrite_due_to_mutation or not hash_val_in_hash_env:
|
| 182 |
+
hash_env[hash_val] = new_node
|
| 183 |
+
token_map[hash_val] = token
|
| 184 |
+
|
| 185 |
+
return new_graph
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def raise_getitems(gm: fx.GraphModule) -> fx.GraphModule:
|
| 189 |
+
# Pre-create a list of nodes to iterate over, as modifying the node order
|
| 190 |
+
# during the loop can lead to infinite loops if not handled properly.
|
| 191 |
+
getitem_nodes = list(
|
| 192 |
+
gm.graph.find_nodes(op="call_function", target=operator.getitem)
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# loop through getitem nodes in the graph and raise them to the parent node
|
| 196 |
+
# in reverse order to preserve their original relative order
|
| 197 |
+
for node in reversed(getitem_nodes):
|
| 198 |
+
if len(node.all_input_nodes) != 1:
|
| 199 |
+
raise AssertionError(
|
| 200 |
+
f"expected node {node.name} to have 1 input node, got {len(node.all_input_nodes)}"
|
| 201 |
+
)
|
| 202 |
+
parent = node.all_input_nodes[0]
|
| 203 |
+
parent.append(node)
|
| 204 |
+
|
| 205 |
+
gm.recompile()
|
| 206 |
+
return gm
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def strip_overloads(gm: fx.GraphModule) -> None:
|
| 210 |
+
"""
|
| 211 |
+
Modifies the target of graph nodes in :attr:`gm` to strip overloads.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
gm(fx.GraphModule): The input Fx graph module to be modified
|
| 215 |
+
"""
|
| 216 |
+
for node in gm.graph.nodes:
|
| 217 |
+
if isinstance(node.target, torch._ops.OpOverload):
|
| 218 |
+
node.target = node.target.overloadpacket
|
| 219 |
+
gm.recompile()
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def get_placeholders(graph: fx.Graph) -> fx.graph._node_list:
|
| 223 |
+
return graph.find_nodes(op="placeholder")
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def get_outputs(graph: fx.Graph) -> list[fx.Node]:
|
| 227 |
+
for node in graph.find_nodes(op="output"):
|
| 228 |
+
return pytree.tree_leaves(node.args[0])
|
| 229 |
+
raise AssertionError("No output node found")
|
venv/lib/python3.14/site-packages/torch/_functorch/compilers.py
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import pickle
|
| 7 |
+
import random
|
| 8 |
+
from contextlib import contextmanager
|
| 9 |
+
from functools import partial
|
| 10 |
+
from typing import Any, TYPE_CHECKING
|
| 11 |
+
from typing_extensions import ParamSpec, TypeVar
|
| 12 |
+
|
| 13 |
+
import sympy
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.fx as fx
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
import torch.utils._pytree as pytree
|
| 19 |
+
from torch import SymInt
|
| 20 |
+
from torch._decomp import get_decompositions
|
| 21 |
+
from torch.fx.experimental.symbolic_shapes import bind_symbols
|
| 22 |
+
|
| 23 |
+
from .aot_autograd import aot_function, aot_module, make_boxed_compiler
|
| 24 |
+
from .compile_utils import strip_overloads
|
| 25 |
+
from .partitioners import (
|
| 26 |
+
default_partition,
|
| 27 |
+
draw_graph,
|
| 28 |
+
min_cut_rematerialization_partition,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if TYPE_CHECKING:
|
| 33 |
+
from collections.abc import Callable, Generator, Sequence
|
| 34 |
+
|
| 35 |
+
from torch.fx.node import Node
|
| 36 |
+
from torch.types import IntLikeType
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
_P = ParamSpec("_P")
|
| 40 |
+
_R = TypeVar("_R")
|
| 41 |
+
|
| 42 |
+
log = logging.getLogger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# These canonicalization are needed here (and not decompositions), as the ops
|
| 46 |
+
# we're trying to canonicalize to CompositeImplicitAutograd.
|
| 47 |
+
def _canonicalize(fx_g: fx.GraphModule) -> fx.GraphModule:
|
| 48 |
+
for node in fx_g.graph.find_nodes(
|
| 49 |
+
op="call_function", target=torch.ops.aten._to_copy
|
| 50 |
+
):
|
| 51 |
+
node.target = torch.ops.aten.to
|
| 52 |
+
fx_g.recompile()
|
| 53 |
+
return fx_g
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@contextmanager
|
| 57 |
+
def _disable_jit_autocast() -> Generator[None, None, None]:
|
| 58 |
+
# pyrefly: ignore [missing-attribute]
|
| 59 |
+
old_jit_autocast_flag = torch._C._jit_set_autocast_mode(False)
|
| 60 |
+
try:
|
| 61 |
+
yield
|
| 62 |
+
finally:
|
| 63 |
+
# pyrefly: ignore [missing-attribute]
|
| 64 |
+
torch._C._jit_set_autocast_mode(old_jit_autocast_flag)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@make_boxed_compiler
|
| 68 |
+
def ts_compile(fx_g: fx.GraphModule, inps: Sequence[Any]) -> torch.jit.ScriptModule:
|
| 69 |
+
"""
|
| 70 |
+
Compiles the :attr:`fx_g` with Torchscript compiler.
|
| 71 |
+
|
| 72 |
+
.. warning::
|
| 73 |
+
This API is experimental and likely to change.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
fx_g(fx.GraphModule): The input Fx graph module to be compiled.
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
Torch scripted model.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
with _disable_jit_autocast():
|
| 83 |
+
strip_overloads(fx_g)
|
| 84 |
+
|
| 85 |
+
for node in fx_g.graph.find_nodes(
|
| 86 |
+
op="call_function", target=torch.ops.aten._to_copy
|
| 87 |
+
):
|
| 88 |
+
if len(node.args) == 1 and len(node.kwargs) == 1 and "dtype" in node.kwargs:
|
| 89 |
+
node.target = torch.ops.aten.to
|
| 90 |
+
|
| 91 |
+
for node in fx_g.graph.nodes:
|
| 92 |
+
new_kwargs = {}
|
| 93 |
+
for k, v in node.kwargs.items():
|
| 94 |
+
if isinstance(v, torch.device):
|
| 95 |
+
v = v.type
|
| 96 |
+
new_kwargs[k] = v
|
| 97 |
+
node.kwargs = new_kwargs
|
| 98 |
+
|
| 99 |
+
fx_g.graph.lint()
|
| 100 |
+
|
| 101 |
+
fx_g.recompile()
|
| 102 |
+
|
| 103 |
+
f = torch.jit.script(fx_g)
|
| 104 |
+
|
| 105 |
+
# pyrefly: ignore [missing-attribute]
|
| 106 |
+
torch._C._jit_pass_remove_mutation(f.graph)
|
| 107 |
+
|
| 108 |
+
f = torch.jit.freeze(f.eval())
|
| 109 |
+
f = torch.jit.optimize_for_inference(f)
|
| 110 |
+
if not any(isinstance(t, torch._subclasses.FakeTensor) for t in inps):
|
| 111 |
+
f(*inps)
|
| 112 |
+
return f
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _draw_graph_compile(
|
| 116 |
+
fx_g: fx.GraphModule, _: Any, name: str, clear_meta: bool = True
|
| 117 |
+
) -> fx.GraphModule:
|
| 118 |
+
print(fx_g.code)
|
| 119 |
+
draw_graph(fx_g, name, clear_meta=clear_meta)
|
| 120 |
+
return fx_g
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def draw_graph_compile(
|
| 124 |
+
name: str,
|
| 125 |
+
) -> Callable[[fx.GraphModule, list[Any]], fx.GraphModule]:
|
| 126 |
+
return make_boxed_compiler(partial(_draw_graph_compile, name=name))
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@make_boxed_compiler
|
| 130 |
+
def nop(fx_g: fx.GraphModule, _: Any) -> fx.GraphModule:
|
| 131 |
+
"""
|
| 132 |
+
Returns the :attr:`fx_g` Fx graph module as it is. This is a no-op compiler
|
| 133 |
+
and can be used to check accuracy.
|
| 134 |
+
|
| 135 |
+
.. warning::
|
| 136 |
+
This API is experimental and likely to change.
|
| 137 |
+
|
| 138 |
+
"""
|
| 139 |
+
return fx_g
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class DebugInterpreter(fx.Interpreter):
|
| 143 |
+
def run(
|
| 144 |
+
self,
|
| 145 |
+
*args: Any,
|
| 146 |
+
initial_env: dict[Node, Any] | None = None,
|
| 147 |
+
enable_io_processing: bool = True,
|
| 148 |
+
) -> Any:
|
| 149 |
+
self.symbol_mapping = bind_symbols(
|
| 150 |
+
# pyrefly: ignore[bad-argument-type]
|
| 151 |
+
self.module,
|
| 152 |
+
*args,
|
| 153 |
+
)
|
| 154 |
+
return super().run(
|
| 155 |
+
*args, initial_env=initial_env, enable_io_processing=enable_io_processing
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def run_node(self, n: Node) -> Any:
|
| 159 |
+
def subst_symint(ni: IntLikeType) -> int:
|
| 160 |
+
if not isinstance(ni, SymInt):
|
| 161 |
+
return ni
|
| 162 |
+
r = sympy.expand(ni.node.expr.xreplace(self.symbol_mapping))
|
| 163 |
+
if not r.is_number:
|
| 164 |
+
raise AssertionError(f"expected r to be a number, got {r}")
|
| 165 |
+
return int(r)
|
| 166 |
+
|
| 167 |
+
def subst_symint_tuple(nis: tuple[IntLikeType, ...]) -> tuple[int, ...]:
|
| 168 |
+
return tuple(subst_symint(ni) for ni in nis)
|
| 169 |
+
|
| 170 |
+
def check_significant_strides(a: torch.Tensor, b: torch.Tensor) -> bool:
|
| 171 |
+
if subst_symint(a.numel()) > 0:
|
| 172 |
+
for idx in range(a.ndim):
|
| 173 |
+
if (
|
| 174 |
+
subst_symint(a.stride(idx)) != b.stride(idx)
|
| 175 |
+
and subst_symint(a.size(idx)) > 1
|
| 176 |
+
):
|
| 177 |
+
return False
|
| 178 |
+
return True
|
| 179 |
+
|
| 180 |
+
def check(nv: torch.Tensor, rv: torch.Tensor, desc: Callable[[], str]) -> None:
|
| 181 |
+
if not callable(desc):
|
| 182 |
+
raise AssertionError(f"expected desc to be callable, got {type(desc)}")
|
| 183 |
+
if nv.dtype != rv.dtype:
|
| 184 |
+
raise AssertionError(f"{desc()}: {nv.dtype} != {rv.dtype}")
|
| 185 |
+
if subst_symint_tuple(nv.size()) != rv.size():
|
| 186 |
+
raise AssertionError(
|
| 187 |
+
f"{desc()}: {nv.size()} aka {subst_symint_tuple(nv.size())} != {rv.size()}"
|
| 188 |
+
)
|
| 189 |
+
same_strides = check_significant_strides(nv, rv)
|
| 190 |
+
if not same_strides:
|
| 191 |
+
raise AssertionError(
|
| 192 |
+
f"{desc()}: {nv.stride()} aka {subst_symint_tuple(nv.stride())} != {rv.stride()}"
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
r = super().run_node(n)
|
| 196 |
+
if "val" in n.meta:
|
| 197 |
+
n_vals, _n_spec = pytree.tree_flatten(n.meta["val"])
|
| 198 |
+
r_vals, _r_spec = pytree.tree_flatten(r)
|
| 199 |
+
# TODO: There is some sort of problem where we record that an
|
| 200 |
+
# operator returned a tuple/list, and then later it turns out the
|
| 201 |
+
# real version of the operator returned a list/tuple. Need to
|
| 202 |
+
# figure out what's actually going on here, the error itself is
|
| 203 |
+
# harmless enough as we only getitem out the outputs.
|
| 204 |
+
# assert n_spec == r_spec, f"{n_spec} != {r_spec}"
|
| 205 |
+
if len(n_vals) != len(r_vals):
|
| 206 |
+
raise AssertionError(f"{len(n_vals)} != {len(r_vals)}")
|
| 207 |
+
for i, nv, rv in zip(range(len(n_vals)), n_vals, r_vals):
|
| 208 |
+
if not isinstance(rv, torch.Tensor):
|
| 209 |
+
continue
|
| 210 |
+
check(nv, rv, lambda: f"output {i} where {self.symbol_mapping}")
|
| 211 |
+
return r
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
@make_boxed_compiler
|
| 215 |
+
def debug_nop(
|
| 216 |
+
fx_g: fx.GraphModule, _: Any
|
| 217 |
+
) -> Callable[[DebugInterpreter, Any, dict[Node, Any] | None, bool], Any]:
|
| 218 |
+
"""
|
| 219 |
+
Returns a (slow) interpreter over the FX graph module that also checks
|
| 220 |
+
various debugging properties (e.g., that tracing strides matched real
|
| 221 |
+
strides.)
|
| 222 |
+
"""
|
| 223 |
+
return DebugInterpreter(fx_g).run
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@make_boxed_compiler
|
| 227 |
+
def simple_ts_compile(fx_g: fx.GraphModule, _: Any) -> torch.jit.ScriptModule:
|
| 228 |
+
strip_overloads(fx_g)
|
| 229 |
+
f = torch.jit.script(fx_g)
|
| 230 |
+
f = torch.jit.freeze(f.eval())
|
| 231 |
+
return f
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def nnc_jit(f: Callable[..., Any]) -> Callable[..., Any]:
|
| 235 |
+
return aot_function(f, simple_ts_compile)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
aten = torch.ops.aten
|
| 239 |
+
default_decompositions = {
|
| 240 |
+
aten.detach,
|
| 241 |
+
aten.gelu_backward,
|
| 242 |
+
aten.leaky_relu_backward,
|
| 243 |
+
aten.sigmoid_backward,
|
| 244 |
+
aten.threshold_backward,
|
| 245 |
+
aten.hardtanh_backward,
|
| 246 |
+
aten.hardsigmoid_backward,
|
| 247 |
+
aten.hardswish_backward,
|
| 248 |
+
aten.tanh_backward,
|
| 249 |
+
aten.silu_backward,
|
| 250 |
+
aten.elu_backward,
|
| 251 |
+
aten.cudnn_batch_norm,
|
| 252 |
+
aten.cudnn_batch_norm_backward,
|
| 253 |
+
aten.masked_fill.Scalar,
|
| 254 |
+
aten.masked_fill.Tensor,
|
| 255 |
+
aten.elu,
|
| 256 |
+
aten.leaky_relu,
|
| 257 |
+
aten.hardtanh,
|
| 258 |
+
aten.hardswish,
|
| 259 |
+
aten.hardsigmoid,
|
| 260 |
+
aten.conj_physical,
|
| 261 |
+
aten.is_same_size,
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
# pyrefly: ignore[bad-argument-type]
|
| 265 |
+
default_decompositions = get_decompositions(default_decompositions)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
@make_boxed_compiler
|
| 269 |
+
def print_compile(fx_g: fx.GraphModule, _: Any) -> fx.GraphModule:
|
| 270 |
+
print(fx_g.code)
|
| 271 |
+
return fx_g
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def memory_efficient_fusion(
|
| 275 |
+
fn: Callable[_P, _R] | nn.Module,
|
| 276 |
+
**kwargs: Any,
|
| 277 |
+
) -> Callable[_P, _R] | nn.Module:
|
| 278 |
+
"""
|
| 279 |
+
Wrapper function over :func:`aot_function` and :func:`aot_module` to perform
|
| 280 |
+
memory efficient fusion. It uses the
|
| 281 |
+
:func:`min_cut_rematerialization_partition` partitioner to perform efficient
|
| 282 |
+
recomputation. It uses NVFuser to compile the generated forward and backward
|
| 283 |
+
graphs.
|
| 284 |
+
|
| 285 |
+
.. warning::
|
| 286 |
+
This API is experimental and likely to change.
|
| 287 |
+
|
| 288 |
+
Args:
|
| 289 |
+
fn (Union[Callable, nn.Module]): A Python function or a ``nn.Module``
|
| 290 |
+
that takes one or more arguments. Must return one or more Tensors.
|
| 291 |
+
**kwargs: Any other overrides you want to make to the settings
|
| 292 |
+
|
| 293 |
+
Returns:
|
| 294 |
+
Returns a ``Callable`` or ``nn.Module`` that retains the eager behavior
|
| 295 |
+
of the original :attr:`fn`, but whose forward and backward graphs have
|
| 296 |
+
gone through recomputation optimizations, and the graphs have been
|
| 297 |
+
compiled with nvfuser.
|
| 298 |
+
|
| 299 |
+
"""
|
| 300 |
+
config = {
|
| 301 |
+
"fw_compiler": ts_compile,
|
| 302 |
+
"bw_compiler": ts_compile,
|
| 303 |
+
"partition_fn": min_cut_rematerialization_partition,
|
| 304 |
+
"decompositions": default_decompositions,
|
| 305 |
+
}
|
| 306 |
+
config.update(kwargs)
|
| 307 |
+
if isinstance(fn, torch.nn.Module):
|
| 308 |
+
return aot_module(fn, **config) # pyrefly: ignore[bad-argument-type]
|
| 309 |
+
else:
|
| 310 |
+
return aot_function(fn, **config) # pyrefly: ignore[bad-argument-type]
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def debug_compile(
|
| 314 |
+
fx_g: fx.GraphModule, inps: Sequence[torch.Tensor]
|
| 315 |
+
) -> torch.jit.ScriptModule:
|
| 316 |
+
fx_g.to_folder("foo")
|
| 317 |
+
print(
|
| 318 |
+
f"""
|
| 319 |
+
##############################################################
|
| 320 |
+
# To minimize FX graph, copy and paste the below and run it #
|
| 321 |
+
##############################################################
|
| 322 |
+
|
| 323 |
+
import torch
|
| 324 |
+
import torch.fx as fx
|
| 325 |
+
from functorch.compile import minifier, check_nvfuser_subprocess, check_nvfuser_correctness_subprocess
|
| 326 |
+
|
| 327 |
+
inps = {[(i.shape, i.dtype) for i in inps]}
|
| 328 |
+
inps = [torch.ones(shape, dtype=dtype, device='cuda') for (shape, dtype) in inps]
|
| 329 |
+
from foo import FxModule
|
| 330 |
+
mod = FxModule().cuda()
|
| 331 |
+
|
| 332 |
+
with torch.jit.fuser("fuser2"):
|
| 333 |
+
# check_nvfuser_subprocess can be replaced with check_nvfuser_correctness_subprocess
|
| 334 |
+
minifier(fx.symbolic_trace(mod), inps, check_nvfuser_subprocess)
|
| 335 |
+
"""
|
| 336 |
+
)
|
| 337 |
+
# pyrefly: ignore[missing-import, missing-module-attribute]
|
| 338 |
+
from foo import FxModule
|
| 339 |
+
|
| 340 |
+
FxModule().cuda()(*inps)
|
| 341 |
+
|
| 342 |
+
return ts_compile(fx_g, inps)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
graph_index: int = 0
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def get_inputs(input_data_path: str) -> list[torch.Tensor]:
|
| 349 |
+
"""
|
| 350 |
+
Return a random input for the given inputs meta generated from _save_fx_default.
|
| 351 |
+
"""
|
| 352 |
+
inputs: list[torch.Tensor] = []
|
| 353 |
+
with open(input_data_path, "rb") as f:
|
| 354 |
+
inputs_meta = pickle.load(f)
|
| 355 |
+
inputs = []
|
| 356 |
+
for meta in inputs_meta:
|
| 357 |
+
if len(meta) == 1:
|
| 358 |
+
type = meta
|
| 359 |
+
input_ = type(random.random())
|
| 360 |
+
else:
|
| 361 |
+
type, shape, _stride, dtype, device = meta
|
| 362 |
+
if dtype in {
|
| 363 |
+
torch.int,
|
| 364 |
+
torch.int32,
|
| 365 |
+
torch.int64,
|
| 366 |
+
torch.bool,
|
| 367 |
+
torch.int,
|
| 368 |
+
torch.uint8,
|
| 369 |
+
int,
|
| 370 |
+
float,
|
| 371 |
+
}:
|
| 372 |
+
input_ = torch.randint(0, 1, shape, dtype=dtype, device=device)
|
| 373 |
+
else:
|
| 374 |
+
input_ = torch.rand(shape, dtype=dtype, device=device)
|
| 375 |
+
inputs.append(input_)
|
| 376 |
+
return inputs
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _save_fx_default(
|
| 380 |
+
current_name: str,
|
| 381 |
+
folder_name: str,
|
| 382 |
+
dump_example_input: bool,
|
| 383 |
+
gm: torch.fx.GraphModule,
|
| 384 |
+
example_inputs: list[torch.Tensor],
|
| 385 |
+
) -> nn.Module:
|
| 386 |
+
"""
|
| 387 |
+
The forward, backward, and joint computation graph will be stored in
|
| 388 |
+
{folder_name}/{current_name}/{current_name}_forward_{graph_index},
|
| 389 |
+
{folder_name}/{current_name}/{current_name}_backward_{graph_index}, and
|
| 390 |
+
{folder_name}/{current_name}/{current_name}_joint_{graph_index} respectively.
|
| 391 |
+
The input shape of the graphs will be stored in the .input files.
|
| 392 |
+
These files can be loaded with pickle,
|
| 393 |
+
and is a list of format (type, shape, stride, dtype, device).
|
| 394 |
+
In the case of type = int or float, it is just (type,).
|
| 395 |
+
For joint graph input, it is a nested list [[],[]]
|
| 396 |
+
where the two inner lists have the same format.
|
| 397 |
+
If dump_example_input is True, example_inputs will be stored in .pt file.
|
| 398 |
+
Since each function might produce multiple graphs,
|
| 399 |
+
the graph_index is used to distinguish difference graphs
|
| 400 |
+
"""
|
| 401 |
+
from functorch.compile import aot_module_simplified
|
| 402 |
+
|
| 403 |
+
def get_input_meta(args: Any) -> list[Any]:
|
| 404 |
+
input_meta = []
|
| 405 |
+
if len(args) > 0 and isinstance(args[0], tuple): # joint input
|
| 406 |
+
input_meta += get_input_meta(args[0])
|
| 407 |
+
input_meta += get_input_meta(args[1])
|
| 408 |
+
return input_meta
|
| 409 |
+
for arg in args:
|
| 410 |
+
if type(arg) is int or type(arg) is float:
|
| 411 |
+
input_meta.append((type(arg),))
|
| 412 |
+
else:
|
| 413 |
+
input_meta.append(
|
| 414 |
+
(type(arg), arg.shape, arg.stride(), arg.dtype, arg.device)
|
| 415 |
+
)
|
| 416 |
+
return input_meta
|
| 417 |
+
|
| 418 |
+
def graph_saver_helper(
|
| 419 |
+
gm_to_save: fx.GraphModule, args: Any, type_name: str
|
| 420 |
+
) -> None:
|
| 421 |
+
global graph_index
|
| 422 |
+
if len(gm_to_save.graph.nodes) == 0:
|
| 423 |
+
log.log(
|
| 424 |
+
logging.WARNING,
|
| 425 |
+
"No nodes in graph {%s}_{%s}_{%s}.",
|
| 426 |
+
current_name,
|
| 427 |
+
type_name,
|
| 428 |
+
graph_index,
|
| 429 |
+
)
|
| 430 |
+
return
|
| 431 |
+
|
| 432 |
+
gm = copy.deepcopy(gm_to_save)
|
| 433 |
+
gm.graph.set_codegen(torch.fx.graph.CodeGen()) # remove codegen
|
| 434 |
+
gm.recompile()
|
| 435 |
+
|
| 436 |
+
input_meta = get_input_meta(args)
|
| 437 |
+
|
| 438 |
+
os.makedirs(f"{folder_name}/{current_name}", exist_ok=True)
|
| 439 |
+
gm.to_folder(
|
| 440 |
+
f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}"
|
| 441 |
+
)
|
| 442 |
+
with open(
|
| 443 |
+
f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}/{current_name}_{type_name}_{graph_index}.input",
|
| 444 |
+
"wb",
|
| 445 |
+
) as f:
|
| 446 |
+
pickle.dump(input_meta, f)
|
| 447 |
+
if dump_example_input:
|
| 448 |
+
torch.save(
|
| 449 |
+
args,
|
| 450 |
+
f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}/{current_name}_{type_name}_{graph_index}.pt", # noqa: B950
|
| 451 |
+
) # noqa: E501
|
| 452 |
+
|
| 453 |
+
def graph_saver_forward(
|
| 454 |
+
gm: fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 455 |
+
) -> fx.GraphModule:
|
| 456 |
+
graph_saver_helper(gm, example_inputs, "forward")
|
| 457 |
+
return gm
|
| 458 |
+
|
| 459 |
+
def graph_saver_backward(
|
| 460 |
+
gm: fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 461 |
+
) -> fx.GraphModule:
|
| 462 |
+
graph_saver_helper(gm, example_inputs, "backward")
|
| 463 |
+
global graph_index
|
| 464 |
+
graph_index += 1
|
| 465 |
+
return gm
|
| 466 |
+
|
| 467 |
+
def graph_saver_joint(
|
| 468 |
+
gm: fx.GraphModule, joint_args: list[torch.Tensor]
|
| 469 |
+
) -> tuple[fx.GraphModule, fx.GraphModule]:
|
| 470 |
+
graph_saver_helper(gm, joint_args, "joint")
|
| 471 |
+
return default_partition(gm, joint_args) # pyrefly: ignore[missing-argument]
|
| 472 |
+
|
| 473 |
+
# pyrefly: ignore[bad-return]
|
| 474 |
+
return aot_module_simplified(
|
| 475 |
+
gm,
|
| 476 |
+
example_inputs,
|
| 477 |
+
fw_compiler=graph_saver_forward, # pyrefly: ignore[bad-argument-type]
|
| 478 |
+
bw_compiler=graph_saver_backward, # pyrefly: ignore[bad-argument-type]
|
| 479 |
+
partition_fn=graph_saver_joint,
|
| 480 |
+
decompositions=default_decompositions, # pyrefly: ignore[bad-argument-type]
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
# WARNING: This isn't tested anywhere!!
|
| 485 |
+
def graph_dumper_aot(
|
| 486 |
+
current_name: str, folder_name: str, dump_example_input: bool = False
|
| 487 |
+
) -> Callable[[bool, nn.Module], Any]:
|
| 488 |
+
"""
|
| 489 |
+
Dump the forward, backward, and joint computation graph.
|
| 490 |
+
Example Usage:
|
| 491 |
+
save_fx_func = graph_dumper_aot(current_name, folder_name, dump_example_input = False)
|
| 492 |
+
optimize_ctx = torchdynamo.optimize(
|
| 493 |
+
save_fx_func
|
| 494 |
+
)
|
| 495 |
+
with torch.enable_grad():
|
| 496 |
+
with optimize_ctx:
|
| 497 |
+
result = forward_and_backward_pass(model, example_inputs)
|
| 498 |
+
"""
|
| 499 |
+
global graph_index
|
| 500 |
+
graph_index = 0
|
| 501 |
+
return partial(_save_fx_default, current_name, folder_name, dump_example_input)
|
venv/lib/python3.14/site-packages/torch/_functorch/config.py
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
from collections.abc import Callable
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
Global flags for aot autograd
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
from typing import Literal, TYPE_CHECKING
|
| 17 |
+
|
| 18 |
+
from torch.utils._config_module import Config, install_config_module
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# [@compile_ignored: debug]
|
| 22 |
+
_save_config_ignore = [
|
| 23 |
+
# callable not serializable
|
| 24 |
+
"joint_custom_pass",
|
| 25 |
+
# callable configs with uuid() for caching, or raw callables
|
| 26 |
+
"activation_memory_budget_runtime_estimator",
|
| 27 |
+
"activation_memory_budget_solver",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Converts torch rng ops to their functional philox rng equivalents. Note that
|
| 32 |
+
# we functionalize only CUDA rng ops today.
|
| 33 |
+
functionalize_rng_ops = False
|
| 34 |
+
|
| 35 |
+
# can be useful for debugging if we are incorrectly creating meta fake tensors
|
| 36 |
+
fake_tensor_allow_meta = os.environ.get("FAKE_ALLOW_META", "1") != "0"
|
| 37 |
+
|
| 38 |
+
# Enables optional asserts in hotpath code to check for errors. If
|
| 39 |
+
# you are seeing weird accuracy problems, try turning this on.
|
| 40 |
+
# This is currently off by default as it will harm tracing time,
|
| 41 |
+
# but it is on by default for aot_eager.
|
| 42 |
+
debug_assert = False
|
| 43 |
+
|
| 44 |
+
debug_partitioner = os.environ.get("AOT_PARTITIONER_DEBUG", "0") != "0"
|
| 45 |
+
|
| 46 |
+
# See # NOTE [Export custom triton op]
|
| 47 |
+
decompose_custom_triton_ops = True
|
| 48 |
+
|
| 49 |
+
static_weight_shapes = True
|
| 50 |
+
|
| 51 |
+
# See https://github.com/pytorch/pytorch/issues/141881
|
| 52 |
+
# Tells partitioner that parameters are free to save for backward.
|
| 53 |
+
treat_parameters_as_free_to_save = True
|
| 54 |
+
|
| 55 |
+
# Applies CSE to the graph before partitioning
|
| 56 |
+
cse = True
|
| 57 |
+
|
| 58 |
+
from torch._environment import is_fbcode
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
enable_autograd_cache: bool = Config(
|
| 62 |
+
justknob="pytorch/remote_cache:enable_local_autograd_cache",
|
| 63 |
+
env_name_force="TORCHINDUCTOR_AUTOGRAD_CACHE",
|
| 64 |
+
default=True,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
autograd_cache_allow_custom_autograd_functions: bool = Config(
|
| 68 |
+
env_name_force="TORCHINDUCTOR_AUTOGRAD_CACHE_ALLOW_CUSTOM_AUTOGRAD", default=False
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# For now, this is just for enabling unit testing in test_aot_autograd_cache.py
|
| 72 |
+
# We will either make this the default with AOTAutogradCache, or
|
| 73 |
+
# we'll just use it in the precompile flow. So there's no
|
| 74 |
+
# need to add env vars or make it configurable
|
| 75 |
+
bundled_autograd_cache: bool = False
|
| 76 |
+
|
| 77 |
+
bypass_autograd_cache_key: bool = False
|
| 78 |
+
|
| 79 |
+
# Whether or not to normalize placeholder names in graphs
|
| 80 |
+
# from dynamo in AOTAutogradCache
|
| 81 |
+
autograd_cache_normalize_inputs = not is_fbcode()
|
| 82 |
+
|
| 83 |
+
# Enable debug mode at first invocation to check if custom ops are valid.
|
| 84 |
+
# When enabled, this checks that custom operators don't violate aliasing constraints.
|
| 85 |
+
#
|
| 86 |
+
# check_custom_op_aliasing: Controls whether to run the custom op aliasing check at all.
|
| 87 |
+
# - When True: The check runs on first invocation of compiled functions.
|
| 88 |
+
# - When False: The check is skipped entirely.
|
| 89 |
+
#
|
| 90 |
+
# error_on_custom_op_aliasing: Controls behavior when a violation is detected.
|
| 91 |
+
# Only has effect when check_custom_op_aliasing is True.
|
| 92 |
+
# - When True: Raises RuntimeError on aliasing violations.
|
| 93 |
+
# - When False: Emits UserWarning on aliasing violations.
|
| 94 |
+
#
|
| 95 |
+
# Deprecated: Custom ops returning aliased outputs is deprecated and will
|
| 96 |
+
# become an error in PyTorch 2.12. Currently error_on_custom_op_aliasing
|
| 97 |
+
# is True only in CI.
|
| 98 |
+
check_custom_op_aliasing = True
|
| 99 |
+
error_on_custom_op_aliasing = bool(os.getenv("CI"))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def remote_autograd_cache_default() -> bool | None:
|
| 103 |
+
if os.environ.get("TORCHINDUCTOR_AUTOGRAD_REMOTE_CACHE") == "1":
|
| 104 |
+
return True
|
| 105 |
+
if os.environ.get("TORCHINDUCTOR_AUTOGRAD_REMOTE_CACHE") == "0":
|
| 106 |
+
return False
|
| 107 |
+
return None
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
enable_remote_autograd_cache = remote_autograd_cache_default()
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# When AOTAutograd regenerates aliased graph outputs,
|
| 114 |
+
# attempt to use functionalization's view-replay logic
|
| 115 |
+
# before falling back to the autograd engine's view replay or as_strided.
|
| 116 |
+
# This can have some perf implications
|
| 117 |
+
# (although for many models this will not matter).
|
| 118 |
+
# (1) If you have many view ops chained together, replaying all of them
|
| 119 |
+
# at runtime can have more overhead compared to a single as_strided call
|
| 120 |
+
# (2) If you are doing training, AsStridedBackward is quite slow,
|
| 121 |
+
# and the individual view op backward formulas will likely be faster.
|
| 122 |
+
# (3) Some backends like XLA do not support as_strided
|
| 123 |
+
|
| 124 |
+
# Temporary hack: disable this flag for internal
|
| 125 |
+
# (needed to fix an internal issue while avoiding bumping XLA pin)
|
| 126 |
+
# eventually: either default this config to false completely
|
| 127 |
+
# once XLA pin update works,
|
| 128 |
+
# or default config to true and fix relevant bugs
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# View replay is currently not compatible with AOTAutogradCache, since
|
| 132 |
+
# FunctionalTensors are not serializable. We'll need to make them
|
| 133 |
+
# serializable before enabling warm cache with this config turned on.
|
| 134 |
+
view_replay_for_aliased_outputs = not is_fbcode()
|
| 135 |
+
|
| 136 |
+
# Restricts the amount of computation AOTAutograd can do.
|
| 137 |
+
# NB: We have essentially disabled this heuristic now. However, this is kept
|
| 138 |
+
# here for now in case it's useful. Setting it low can artificially reduce the
|
| 139 |
+
# amount of recomputation AOTAutograd performs, although not in any kind of
|
| 140 |
+
# principled way.
|
| 141 |
+
max_dist_from_bw = 1000
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# Bans recomputation of nodes that are reading from nodes that are far before
|
| 145 |
+
# the current node
|
| 146 |
+
ban_recompute_used_far_apart = True
|
| 147 |
+
# Breaks up long chain of fusible ops, as otherwise we can have an arbitrarily
|
| 148 |
+
# long chain of recomputation in the backwards pass.
|
| 149 |
+
ban_recompute_long_fusible_chains = True
|
| 150 |
+
# Bans recomputation of nodes that must be materialized in the backwards pass
|
| 151 |
+
# (used by a non-fusible node)
|
| 152 |
+
ban_recompute_materialized_backward = True
|
| 153 |
+
# Chooses to ban recomputation of nodes based off an allowlist. Setting it to
|
| 154 |
+
# False changes it to use a denylist. Main change is on operators like
|
| 155 |
+
# sort/pool/stuff that isn't cheap enough to be fusible for free but also isn't
|
| 156 |
+
# that expensive
|
| 157 |
+
ban_recompute_not_in_allowlist = True
|
| 158 |
+
# Chooses to ban recomputation of reductions. This is generally a good idea, as
|
| 159 |
+
# the result of reductions is generally very small but recomputing reductions in
|
| 160 |
+
# a fusion can be expensive.
|
| 161 |
+
ban_recompute_reductions = True
|
| 162 |
+
# Prevents the partitioner from ever saving views (i.e. always recompute them).
|
| 163 |
+
# Generally a good idea since views are free to recompute.
|
| 164 |
+
recompute_views = False
|
| 165 |
+
# Set this flag to enable considering non-built-in ops, including triton and custom
|
| 166 |
+
# ops, for recomputation during the knapsack optimization solver.
|
| 167 |
+
is_non_builtin_to_include = False
|
| 168 |
+
|
| 169 |
+
# Rematerialize AC nodes for graphs with forward+loss+backward in one graph.
|
| 170 |
+
# This optimization minimizes activation checkpoint node lifetimes by computing them
|
| 171 |
+
# just-in-time. For AC nodes only used in backward, they are deferred to backward region
|
| 172 |
+
# instead of being computed and saved in forward. This reduces peak memory usage.
|
| 173 |
+
# Note: This only applies to forward+loss+backward graphs where torch.autograd.grad is allowed
|
| 174 |
+
# in the graph. Joint graphs (standard AOTAutograd) use the partitioner instead.
|
| 175 |
+
remat_using_tags_for_fwd_loss_bwd_graph = True
|
| 176 |
+
|
| 177 |
+
# By default, the partitioner is purely trying to optimize for runtime (although
|
| 178 |
+
# it should always use less memory than eager)
|
| 179 |
+
# This knob controls the partitioner to make that tradeoff for you, choosing the
|
| 180 |
+
# fastest option that saves less activations than the memory budget.
|
| 181 |
+
# Specifically, 0.0 corresponds to the activation memory from applying
|
| 182 |
+
# activation checkpointing to the full compiled region, and 1.0 corresponds to
|
| 183 |
+
# the activation memory from the default runtime-optimized strategy. So, 0.4
|
| 184 |
+
# would result in a strategy that saves 40% of the activations compared to the
|
| 185 |
+
# default strategy.
|
| 186 |
+
# It solves a 0-1 knapsack to find the minimum recompute necessary to stay below
|
| 187 |
+
# the activation memory budget.
|
| 188 |
+
# NOTE: This *cannot* be treated as
|
| 189 |
+
activation_memory_budget = 1.0
|
| 190 |
+
|
| 191 |
+
# This controls how we estimate the runtime when deciding what the cheapest
|
| 192 |
+
# operators to recompute are. The 3 options are
|
| 193 |
+
# "flops": Bases it off of the flop count provided by torch.utils.flop_counter
|
| 194 |
+
# "profile": Benchmarks each operator to come up with a runtime
|
| 195 |
+
# "testing": Returns 1 for everything
|
| 196 |
+
activation_memory_budget_runtime_estimator = "flops"
|
| 197 |
+
|
| 198 |
+
# This controls the solver used for the 0-1 knapsack. By default we use a
|
| 199 |
+
# quantized DP solution ("dp"). The other approaches are a "greedy", an "ilp"
|
| 200 |
+
# (which has a scipy dependency) and "dp_knapsack_sliding_hirschberg", which
|
| 201 |
+
# used memory-efficient quantized DP solution
|
| 202 |
+
activation_memory_budget_solver = "dp"
|
| 203 |
+
|
| 204 |
+
# This dumps out a SVG visualization of the expected runtime vs. activation
|
| 205 |
+
# memory tradeoffs for all memory budget values from 0 to 1 in increments of
|
| 206 |
+
# 0.5. See an example here:
|
| 207 |
+
# https://github.com/pytorch/pytorch/pull/126320#discussion_r1625104015
|
| 208 |
+
visualize_memory_budget_pareto = (
|
| 209 |
+
os.environ.get("PARTITIONER_MEMORY_BUDGET_PARETO", "0") == "1"
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
# This controls the directory in which to dump the SVG plot with the pareto
|
| 213 |
+
# frontier of the activation checkpointing memory-vs-runtime tradeoffs.
|
| 214 |
+
memory_budget_pareto_dir = os.environ.get("PARTITIONER_MEMORY_BUDGET_PARETO_DIR")
|
| 215 |
+
|
| 216 |
+
# Sets all of the ban_recompute heuristics to False except ban_recompute_reductions
|
| 217 |
+
# Generally, this will probably result in some memory improvement, but at the
|
| 218 |
+
# cost of some performance
|
| 219 |
+
aggressive_recomputation = False
|
| 220 |
+
|
| 221 |
+
# activation offloading enablement (testing purpose)
|
| 222 |
+
enable_activation_offloading = False
|
| 223 |
+
|
| 224 |
+
# activation offloading with separate CUDA stream
|
| 225 |
+
activation_offload_separate_stream = False
|
| 226 |
+
|
| 227 |
+
# activation offloading wait sinking when using separate stream (fwd graph)
|
| 228 |
+
activation_offload_sink_wait = False
|
| 229 |
+
|
| 230 |
+
# activation reloading with prefetching when using separate streams (bwd graph)
|
| 231 |
+
activation_reload_prefetch = False
|
| 232 |
+
|
| 233 |
+
# CPU ↔ GPU bandwidth in GB/s, used to estimate transfer times for prefetch
|
| 234 |
+
# scheduling. This is hardware-specific and should be set by the user.
|
| 235 |
+
activation_offload_cpu_gpu_bw: float = 50.0
|
| 236 |
+
|
| 237 |
+
# If FakeTensor.data_ptr() should error.
|
| 238 |
+
# This option is independent of AOTAutograd and torch.compile, but our policy
|
| 239 |
+
# is to turn it off during torch.compile.
|
| 240 |
+
fake_tensor_allow_unsafe_data_ptr_access = True
|
| 241 |
+
|
| 242 |
+
# Unlifts effect tokens from the inputs/outputs in the traced graph and instead
|
| 243 |
+
# inserts make_token/sink_token calls in the graph to create tokens and then
|
| 244 |
+
# sink them at the end. Note that this means the graph is no longer functional
|
| 245 |
+
# which may lead to silent errors unless the backend knows how to handle the
|
| 246 |
+
# tokens.
|
| 247 |
+
unlift_effect_tokens = False
|
| 248 |
+
|
| 249 |
+
# NOTE: [The default layout constraint for custom operators.]
|
| 250 |
+
# This must be the name of one of the layout constraint tags
|
| 251 |
+
# (that is, one of {"needs_fixed_stride_order", "flexible_layout"}),
|
| 252 |
+
# If the custom op does not have a layout constraint tag already
|
| 253 |
+
# then we assume the following applies.
|
| 254 |
+
#
|
| 255 |
+
# This config is respected by Inductor and we recommend other backends also
|
| 256 |
+
# respect it.
|
| 257 |
+
# This config is in torch._functorch and not torch._inductor because it affects
|
| 258 |
+
# ProxyTensor tracing.
|
| 259 |
+
custom_op_default_layout_constraint: Literal[
|
| 260 |
+
"needs_exact_strides", "needs_fixed_stride_order", "flexible_layout"
|
| 261 |
+
] = "needs_exact_strides"
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
# Run aot eager decomp partition with CrossRefFakeMode
|
| 265 |
+
# options = False, "all", "custom_ops"
|
| 266 |
+
fake_tensor_crossref = False
|
| 267 |
+
|
| 268 |
+
# This mode specifies that we should also keep track of the real
|
| 269 |
+
# tensor along with the fake tensor, and do real compute. While
|
| 270 |
+
# seemingly this eliminates the whole point of fake tensors, there are
|
| 271 |
+
# two obvious use cases for it:
|
| 272 |
+
#
|
| 273 |
+
# 1. When users call item()/other data dependent operations,
|
| 274 |
+
# if we propagate_real_tensors we are able to determine what
|
| 275 |
+
# the true value is and keep going.
|
| 276 |
+
#
|
| 277 |
+
# 2. It can be useful for testing, when you want to see if the fake
|
| 278 |
+
# and real tensors agree with each other. (Note that there are
|
| 279 |
+
# currently known inaccuracies in how we clone real tensors, that
|
| 280 |
+
# would have to be tightened up for this to be useful in this
|
| 281 |
+
# case.)
|
| 282 |
+
#
|
| 283 |
+
# Note that fake tensors are typically understood to be cheap to store
|
| 284 |
+
# indefinitely, so we tend to hold on to them longer than we would
|
| 285 |
+
# hold onto the real tensors. So we also support you explicitly
|
| 286 |
+
# deallocating the real tensor associated with a fake tensor, at which
|
| 287 |
+
# point we will stop propagating real tensors.
|
| 288 |
+
#
|
| 289 |
+
# One more thing: when you provide a real tensor to fakeify, we will
|
| 290 |
+
# clone it, so that we can safely perform mutations on it if necessary.
|
| 291 |
+
# This will increase live memory usage. This could potentially be
|
| 292 |
+
# optimized by using COW. We also currently do not faithfully
|
| 293 |
+
# maintain autograd metadata on the real tensor; this is fine because
|
| 294 |
+
# AOTAutograd will only use the fake tensor to determine leafness/etc
|
| 295 |
+
# of tensors in question.
|
| 296 |
+
fake_tensor_propagate_real_tensors = False
|
| 297 |
+
|
| 298 |
+
# AOTDispatcher traces out a backward graph at the time of the forward pass.
|
| 299 |
+
# This flag controls whether or not that backward graph gets autocast behavior
|
| 300 |
+
# applied to it.
|
| 301 |
+
#
|
| 302 |
+
# The options are either:
|
| 303 |
+
# - "same_as_forward". We assume that the backward of the torch.compile'ed region
|
| 304 |
+
# will be run under the same autocast context manager that the region was run
|
| 305 |
+
# under. This is equivalent to running the following code in eager:
|
| 306 |
+
#
|
| 307 |
+
# with torch.amp.autocast(...):
|
| 308 |
+
# y = region(x)
|
| 309 |
+
# ...
|
| 310 |
+
# z.backward()
|
| 311 |
+
#
|
| 312 |
+
# - "off". We assume that the backward of the torch.compile'd region will
|
| 313 |
+
# not be run under any autocast context managers.
|
| 314 |
+
# This is equivalent to running the following code in eager:
|
| 315 |
+
#
|
| 316 |
+
# with torch.amp.autocast(...):
|
| 317 |
+
# y = region(x)
|
| 318 |
+
# ...
|
| 319 |
+
# z.backward()
|
| 320 |
+
#
|
| 321 |
+
# - or a list of kwargs dicts that represent an autocast context manager to turn
|
| 322 |
+
# on during the backward pass.
|
| 323 |
+
#
|
| 324 |
+
# e.g. [{"device_type": "cuda"}] is equivalent to running the following code in eager:
|
| 325 |
+
#
|
| 326 |
+
# y = region(x)
|
| 327 |
+
# ...
|
| 328 |
+
# with torch.amp.autocast(device="cuda"):
|
| 329 |
+
# z.backward()
|
| 330 |
+
backward_pass_autocast = "same_as_forward"
|
| 331 |
+
|
| 332 |
+
# This controls whether we collect donated buffers. This flag must be set
|
| 333 |
+
# False if a user wants to retain_graph=True for backward.
|
| 334 |
+
donated_buffer = not is_fbcode()
|
| 335 |
+
|
| 336 |
+
# Controls the default graph output format used by draw_graph
|
| 337 |
+
# Supported formats are defined here https://graphviz.org/docs/outputs/
|
| 338 |
+
torch_compile_graph_format = os.environ.get("TORCH_COMPILE_GRAPH_FORMAT", "svg")
|
| 339 |
+
|
| 340 |
+
# Valid only if fake_tensor_propagate_real_tensors = True; if a fake-real
|
| 341 |
+
# kernel mismatch is detected, bypasses by making a fake kernel from the
|
| 342 |
+
# real tensor outputs.
|
| 343 |
+
generate_fake_kernels_from_real_mismatches = False
|
| 344 |
+
|
| 345 |
+
# When there are device mismatches in FakeTensor device propagation,
|
| 346 |
+
# prefer a specific device type over others. This is particularly useful
|
| 347 |
+
# in full compiled mode where intermediate tensors with device mismatches
|
| 348 |
+
# represent only logical differences during compilation - these intermediate
|
| 349 |
+
# tensors will never physically materialize in the binary execution, so the
|
| 350 |
+
# device mismatch is not a real runtime concern. Enabling this allows the
|
| 351 |
+
# compiler to proceed with compilation by choosing the preferred device type
|
| 352 |
+
# for consistency. For example, set to "mtia" to prefer MTIA devices over
|
| 353 |
+
# CPU, or "cuda" to prefer CUDA devices over CPU.
|
| 354 |
+
fake_tensor_prefer_device_type: str | None = None
|
| 355 |
+
|
| 356 |
+
# CUDAGraph safe run_with_rng functionalization.
|
| 357 |
+
# TODO: turn on by default
|
| 358 |
+
graphsafe_rng_functionalization = True
|
| 359 |
+
|
| 360 |
+
# Whether or not to eagerly compile the backward
|
| 361 |
+
# used by AOT compile and other settings
|
| 362 |
+
# TODO: once AOT compile calls aot autograd directly instead of
|
| 363 |
+
# through compile_fx, we can remove this
|
| 364 |
+
force_non_lazy_backward_lowering = False
|
| 365 |
+
|
| 366 |
+
# only for testing, used to turn functionalization off in AOTDispatcher
|
| 367 |
+
_test_disable_functionalization = True
|
| 368 |
+
|
| 369 |
+
# Error on BypassAOTAutogradCache instead of just a warning
|
| 370 |
+
# Used for tests
|
| 371 |
+
strict_autograd_cache = False
|
| 372 |
+
|
| 373 |
+
# Note [Recomputing collectives in the partitioner]
|
| 374 |
+
# The purpose of this config is as follows:
|
| 375 |
+
# - We have many passes in the compiler (min-cut partitioning, DCE, etc)
|
| 376 |
+
# which can reorder or delete duplicate nodes in the graph
|
| 377 |
+
# - If any of these passes reorder/delete/duplicate a collective
|
| 378 |
+
# in a setting where the compiler is being run independently on multiple
|
| 379 |
+
# ranks, we run the risk that the compiler will make a different decision on
|
| 380 |
+
# different ranks, resulting in a NCCL hang when using torch.compile
|
| 381 |
+
# To handle this, we will (by default) ensure that collectives are not modified
|
| 382 |
+
# by the compiler.
|
| 383 |
+
#
|
| 384 |
+
# A few examples:
|
| 385 |
+
# - don't dead-code-eliminate collectives
|
| 386 |
+
# (in case they are dead on rank i but not rank j)
|
| 387 |
+
# - don't recompute collectives in partitioning
|
| 388 |
+
# (in case we recompute on rank i but not rank j)
|
| 389 |
+
#
|
| 390 |
+
# Today this flag **must** be set to false, but eventually
|
| 391 |
+
# we want the option to set it to true.
|
| 392 |
+
# In order to potentially optimize collectives, we'll need the compiler
|
| 393 |
+
# to broadcast information across ranks at compile time to ensure
|
| 394 |
+
# that any decisions on collectives are made consistently.
|
| 395 |
+
unsafe_allow_optimization_of_collectives = False
|
| 396 |
+
|
| 397 |
+
# See Note [AOTAutograd Tangent Subclassness for mutated inputs]
|
| 398 |
+
# TODO(ivankobzarev): Remove this config, being able to deduce it compile time.
|
| 399 |
+
disable_guess_zero_tangent_for_mutated_input_subclass = False
|
| 400 |
+
|
| 401 |
+
# See Note [Tangents memory format]
|
| 402 |
+
# By default tangents strideness is guessed to be contiguous,
|
| 403 |
+
# At runtime non contiguous tangents will be coerced to be contiguous.
|
| 404 |
+
# This config changes this guess for tangents strides to be the same as outputs.
|
| 405 |
+
# TODO(ivankobzarev): Remove this config once extra memory usage is investigated.
|
| 406 |
+
guess_tangent_strides_as_outputs = not is_fbcode()
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
# This is a temporary config to ensure all ranks take the same decision in the partitioner
|
| 410 |
+
# it will ultimately be removed once we share size_hints across ranks through compiler collectives
|
| 411 |
+
_sync_decision_cross_ranks = False
|
| 412 |
+
|
| 413 |
+
# By default apply inlined saved_tensors_hooks only for "donated" buffers.
|
| 414 |
+
# "donated" buffers are invisible to the user, they are intermediates of the forward graph.
|
| 415 |
+
# Applying saved tensors hooks for memory optimizations only for intermediates
|
| 416 |
+
# guarantees that original saved tensors could be deallocated.
|
| 417 |
+
# This config enables saved_tensors_hooks are applied for **all** saved tensors,
|
| 418 |
+
# that could include inputs, parameters, outputs.
|
| 419 |
+
# "donated" - applied only to saved intermediates of the graph
|
| 420 |
+
# "no_static" - applied to all saved but not "static"
|
| 421 |
+
# (this includes parameters and user marked as static)
|
| 422 |
+
# "all" - no filtering, everything saved for backward.
|
| 423 |
+
saved_tensors_hooks_filtering_mode = "donated"
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
# This callback is invoked on the joint graph before partitioning
|
| 427 |
+
joint_custom_pass: Callable = None # type: ignore[assignment]
|
| 428 |
+
|
| 429 |
+
force_autograd_cache = False
|
| 430 |
+
|
| 431 |
+
# Note [Selective Decomposition]
|
| 432 |
+
# This config allows selective decomposition of certain operators in the graph.
|
| 433 |
+
# When True, it does NOT decompose any nodes, except those nodes that users explicitly
|
| 434 |
+
# annotated with regional inductor compile. Please read torch.fx.passes.regional_inductor
|
| 435 |
+
# on to explicitly annotate. This is currently only used by inductor lite mode.
|
| 436 |
+
selective_decompose: bool = False
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
if TYPE_CHECKING:
|
| 440 |
+
from torch.utils._config_typing import * # noqa: F401, F403
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
# adds patch, save_config, invalid config checks, etc
|
| 444 |
+
install_config_module(sys.modules[__name__])
|
venv/lib/python3.14/site-packages/torch/_functorch/deprecated.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The APIs in this file are exposed as `functorch.*`. They are thin wrappers
|
| 3 |
+
around the torch.func.* APIs that have deprecation warnings -- we're trying
|
| 4 |
+
to move people to the torch.func.* equivalents.
|
| 5 |
+
|
| 6 |
+
NB: We don't use *args, **kwargs in the signatures because that changes the
|
| 7 |
+
documentation.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import textwrap
|
| 13 |
+
import warnings
|
| 14 |
+
from typing import Any, TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
import torch._functorch.apis as apis
|
| 17 |
+
import torch._functorch.eager_transforms as _impl
|
| 18 |
+
import torch._functorch.make_functional as _nn_impl
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from collections.abc import Callable
|
| 24 |
+
|
| 25 |
+
from torch._functorch.eager_transforms import argnums_t
|
| 26 |
+
from torch._functorch.vmap import in_dims_t, out_dims_t
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_warning(
|
| 30 |
+
api: str, new_api: str | None = None, replace_newlines: bool = False
|
| 31 |
+
) -> str:
|
| 32 |
+
if new_api is None:
|
| 33 |
+
new_api = f"torch.func.{api}"
|
| 34 |
+
warning = (
|
| 35 |
+
f"We've integrated functorch into PyTorch. As the final step of the \n"
|
| 36 |
+
f"integration, `functorch.{api}` is deprecated as of PyTorch \n"
|
| 37 |
+
f"2.0 and will be deleted in a future version of PyTorch >= 2.3. \n"
|
| 38 |
+
f"Please use `{new_api}` instead; see the PyTorch 2.0 release notes \n"
|
| 39 |
+
f"and/or the `torch.func` migration guide for more details \n"
|
| 40 |
+
f"https://pytorch.org/docs/main/func.migrating.html"
|
| 41 |
+
)
|
| 42 |
+
if replace_newlines:
|
| 43 |
+
warning = warning.replace("\n", "")
|
| 44 |
+
return warning
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def warn_deprecated(api: str, new_api: str | None = None) -> None:
|
| 48 |
+
warning = get_warning(api, new_api, replace_newlines=True)
|
| 49 |
+
warnings.warn(warning, FutureWarning, stacklevel=3)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def setup_docs(
|
| 53 |
+
functorch_api: Callable[..., Any],
|
| 54 |
+
torch_func_api: Callable[..., Any] | None = None,
|
| 55 |
+
new_api_name: str | None = None,
|
| 56 |
+
) -> None:
|
| 57 |
+
api_name = functorch_api.__name__
|
| 58 |
+
if torch_func_api is None:
|
| 59 |
+
torch_func_api = getattr(_impl, api_name)
|
| 60 |
+
# See https://docs.python.org/3/using/cmdline.html#cmdoption-OO
|
| 61 |
+
if torch_func_api.__doc__ is None:
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
warning = get_warning(api_name, new_api_name)
|
| 65 |
+
warning_note = "\n.. warning::\n\n" + textwrap.indent(warning, " ")
|
| 66 |
+
warning_note = textwrap.indent(warning_note, " ")
|
| 67 |
+
functorch_api.__doc__ = torch_func_api.__doc__ + warning_note
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def vmap(
|
| 71 |
+
func: Callable[..., Any],
|
| 72 |
+
in_dims: in_dims_t = 0,
|
| 73 |
+
out_dims: out_dims_t = 0,
|
| 74 |
+
randomness: str = "error",
|
| 75 |
+
*,
|
| 76 |
+
chunk_size: int | None = None,
|
| 77 |
+
) -> Callable[..., Any]:
|
| 78 |
+
warn_deprecated("vmap", "torch.vmap")
|
| 79 |
+
return apis.vmap(func, in_dims, out_dims, randomness, chunk_size=chunk_size)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def grad(
|
| 83 |
+
func: Callable[..., Any], argnums: argnums_t = 0, has_aux: bool = False
|
| 84 |
+
) -> Callable[..., Any]:
|
| 85 |
+
warn_deprecated("grad")
|
| 86 |
+
return apis.grad(func, argnums, has_aux)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def grad_and_value(
|
| 90 |
+
func: Callable[..., Any], argnums: argnums_t = 0, has_aux: bool = False
|
| 91 |
+
) -> Callable[..., Any]:
|
| 92 |
+
warn_deprecated("grad_and_value")
|
| 93 |
+
return apis.grad_and_value(func, argnums, has_aux)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def vjp(func: Callable[..., Any], *primals: Any, has_aux: bool = False) -> Any:
|
| 97 |
+
warn_deprecated("vjp")
|
| 98 |
+
return _impl.vjp(func, *primals, has_aux=has_aux)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def jvp(
|
| 102 |
+
func: Callable[..., Any],
|
| 103 |
+
primals: Any,
|
| 104 |
+
tangents: Any,
|
| 105 |
+
*,
|
| 106 |
+
strict: bool = False,
|
| 107 |
+
has_aux: bool = False,
|
| 108 |
+
) -> Any:
|
| 109 |
+
warn_deprecated("jvp")
|
| 110 |
+
return _impl.jvp(func, primals, tangents, strict=strict, has_aux=has_aux)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def jacrev(
|
| 114 |
+
func: Callable[..., Any],
|
| 115 |
+
argnums: int | tuple[int, ...] = 0,
|
| 116 |
+
*,
|
| 117 |
+
has_aux: bool = False,
|
| 118 |
+
chunk_size: int | None = None,
|
| 119 |
+
_preallocate_and_copy: bool = False,
|
| 120 |
+
) -> Callable[..., Any]:
|
| 121 |
+
warn_deprecated("jacrev")
|
| 122 |
+
return _impl.jacrev(
|
| 123 |
+
func,
|
| 124 |
+
argnums,
|
| 125 |
+
has_aux=has_aux,
|
| 126 |
+
chunk_size=chunk_size,
|
| 127 |
+
_preallocate_and_copy=_preallocate_and_copy,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def jacfwd(
|
| 132 |
+
func: Callable[..., Any],
|
| 133 |
+
argnums: argnums_t = 0,
|
| 134 |
+
has_aux: bool = False,
|
| 135 |
+
*,
|
| 136 |
+
randomness: str = "error",
|
| 137 |
+
) -> Callable[..., Any]:
|
| 138 |
+
warn_deprecated("jacfwd")
|
| 139 |
+
return _impl.jacfwd(func, argnums, has_aux, randomness=randomness)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def hessian(func: Callable[..., Any], argnums: int = 0) -> Callable[..., Any]:
|
| 143 |
+
warn_deprecated("hessian")
|
| 144 |
+
return _impl.hessian(func, argnums=argnums)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def functionalize(
|
| 148 |
+
func: Callable[..., Any], *, remove: str = "mutations"
|
| 149 |
+
) -> Callable[..., Any]:
|
| 150 |
+
warn_deprecated("functionalize")
|
| 151 |
+
return _impl.functionalize(func, remove=remove)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def make_functional(model: nn.Module, disable_autograd_tracking: bool = False) -> Any:
|
| 155 |
+
warn_deprecated("make_functional", "torch.func.functional_call")
|
| 156 |
+
return _nn_impl.make_functional(model, disable_autograd_tracking)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def make_functional_with_buffers(
|
| 160 |
+
model: nn.Module, disable_autograd_tracking: bool = False
|
| 161 |
+
) -> Any:
|
| 162 |
+
warn_deprecated("make_functional_with_buffers", "torch.func.functional_call")
|
| 163 |
+
return _nn_impl.make_functional_with_buffers(model, disable_autograd_tracking)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def combine_state_for_ensemble(models: list[nn.Module]) -> Any:
|
| 167 |
+
warn_deprecated("combine_state_for_ensemble", "torch.func.stack_module_state")
|
| 168 |
+
return _nn_impl.combine_state_for_ensemble(models)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
setup_docs(vmap, apis.vmap, "torch.vmap")
|
| 172 |
+
setup_docs(grad, apis.grad)
|
| 173 |
+
setup_docs(grad_and_value, apis.grad_and_value)
|
| 174 |
+
setup_docs(vjp)
|
| 175 |
+
setup_docs(jvp)
|
| 176 |
+
setup_docs(jacrev)
|
| 177 |
+
setup_docs(jacfwd)
|
| 178 |
+
setup_docs(hessian)
|
| 179 |
+
setup_docs(functionalize)
|
| 180 |
+
setup_docs(make_functional, _nn_impl.make_functional, "torch.func.functional_call")
|
| 181 |
+
setup_docs(
|
| 182 |
+
make_functional_with_buffers, _nn_impl.make_functional, "torch.func.functional_call"
|
| 183 |
+
)
|
| 184 |
+
setup_docs(
|
| 185 |
+
combine_state_for_ensemble,
|
| 186 |
+
_nn_impl.combine_state_for_ensemble,
|
| 187 |
+
"torch.func.stack_module_state",
|
| 188 |
+
)
|
venv/lib/python3.14/site-packages/torch/_functorch/eager_transforms.py
ADDED
|
@@ -0,0 +1,1951 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import contextlib
|
| 10 |
+
from functools import partial, wraps
|
| 11 |
+
from typing import Any, overload, TYPE_CHECKING
|
| 12 |
+
from typing_extensions import ParamSpec, TypeVar
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.autograd.forward_ad as fwAD
|
| 16 |
+
from torch._C._functorch import (
|
| 17 |
+
_assert_wrapped_functional, # type: ignore[attr-defined]
|
| 18 |
+
_func_decrement_nesting, # type: ignore[attr-defined]
|
| 19 |
+
_func_increment_nesting, # type: ignore[attr-defined]
|
| 20 |
+
_grad_decrement_nesting,
|
| 21 |
+
_grad_increment_nesting,
|
| 22 |
+
_jvp_decrement_nesting,
|
| 23 |
+
_jvp_increment_nesting,
|
| 24 |
+
_propagate_functional_input_mutation, # type: ignore[attr-defined]
|
| 25 |
+
_unwrap_for_grad,
|
| 26 |
+
_unwrap_functional_tensor,
|
| 27 |
+
_wrap_for_grad,
|
| 28 |
+
_wrap_functional_tensor,
|
| 29 |
+
get_inplace_requires_grad_allowed,
|
| 30 |
+
get_unwrapped,
|
| 31 |
+
is_functorch_wrapped_tensor,
|
| 32 |
+
set_inplace_requires_grad_allowed,
|
| 33 |
+
)
|
| 34 |
+
from torch._functorch.utils import argnums_t, exposed_in
|
| 35 |
+
from torch._subclasses.functional_tensor import FunctionalTensor
|
| 36 |
+
from torch.fx.experimental import const_fold
|
| 37 |
+
from torch.fx.experimental.proxy_tensor import make_fx
|
| 38 |
+
from torch.utils import _pytree as pytree
|
| 39 |
+
from torch.utils._pytree import (
|
| 40 |
+
tree_flatten,
|
| 41 |
+
tree_map,
|
| 42 |
+
tree_map_,
|
| 43 |
+
tree_map_only,
|
| 44 |
+
tree_unflatten,
|
| 45 |
+
treespec_pprint,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
from .apis import vmap
|
| 49 |
+
from .vmap import doesnt_support_saved_tensors_hooks, get_chunk_sizes
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if TYPE_CHECKING:
|
| 53 |
+
from collections.abc import Callable, Generator, Sequence
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
_P = ParamSpec("_P")
|
| 57 |
+
_R = TypeVar("_R")
|
| 58 |
+
_T = TypeVar("_T")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def lazy_dynamo_disallow(func: Callable[_P, _R]) -> Callable[_P, _R]:
|
| 62 |
+
import torch._dynamo
|
| 63 |
+
|
| 64 |
+
return torch._dynamo.disallow_in_graph(func)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@contextlib.contextmanager
|
| 68 |
+
def enable_inplace_requires_grad(enabled: bool) -> Generator[None, None, None]:
|
| 69 |
+
prev_state = get_inplace_requires_grad_allowed()
|
| 70 |
+
set_inplace_requires_grad_allowed(enabled)
|
| 71 |
+
try:
|
| 72 |
+
yield
|
| 73 |
+
finally:
|
| 74 |
+
set_inplace_requires_grad_allowed(prev_state)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _set_tensor_requires_grad(x: torch.Tensor) -> torch.Tensor:
|
| 78 |
+
# avoid graph-break on x.requires_grad_()
|
| 79 |
+
# https://github.com/pytorch/pytorch/pull/110053
|
| 80 |
+
return x.requires_grad_()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _create_differentiable(inps: Any, level: int | None = None) -> Any:
|
| 84 |
+
def create_differentiable(x: torch.Tensor | Any) -> torch.Tensor:
|
| 85 |
+
if isinstance(x, torch.Tensor):
|
| 86 |
+
with enable_inplace_requires_grad(True):
|
| 87 |
+
return _set_tensor_requires_grad(x)
|
| 88 |
+
raise ValueError(f"Thing passed to transform API must be Tensor, got {type(x)}")
|
| 89 |
+
|
| 90 |
+
return tree_map(create_differentiable, inps)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
_Tensors = torch.Tensor | tuple[torch.Tensor, ...]
|
| 94 |
+
_TensorsT = TypeVar("_TensorsT", bound=_Tensors)
|
| 95 |
+
_TensorsU = TypeVar("_TensorsU", bound=_Tensors)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _undo_create_differentiable(inps: _TensorsT, level: int | None = None) -> _TensorsT:
|
| 99 |
+
def unwrap_tensors(x: _TensorsU) -> _TensorsU:
|
| 100 |
+
if isinstance(x, torch.Tensor):
|
| 101 |
+
if level is None:
|
| 102 |
+
raise AssertionError("level must not be None when unwrapping tensors")
|
| 103 |
+
# pyrefly: ignore[bad-return]
|
| 104 |
+
return _unwrap_for_grad(x, level)
|
| 105 |
+
# TODO: Remove the following hack for namedtuples
|
| 106 |
+
if isinstance(x, tuple):
|
| 107 |
+
return tree_map(unwrap_tensors, tuple(x))
|
| 108 |
+
|
| 109 |
+
raise RuntimeError(f"Expected tensors, got unsupported type {type(x)}")
|
| 110 |
+
|
| 111 |
+
return tree_map(unwrap_tensors, inps)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _is_differentiable(maybe_tensor: object) -> bool:
|
| 115 |
+
if not isinstance(maybe_tensor, torch.Tensor):
|
| 116 |
+
return False
|
| 117 |
+
return maybe_tensor.requires_grad
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _any_differentiable(
|
| 121 |
+
tensor_or_tuple_of_tensors: _Tensors,
|
| 122 |
+
) -> bool:
|
| 123 |
+
flat_args, _ = tree_flatten(tensor_or_tuple_of_tensors)
|
| 124 |
+
return any(tuple(map(_is_differentiable, flat_args)))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _wrap_tensor_for_grad(maybe_tensor: _T, level: int) -> _T:
|
| 128 |
+
if not isinstance(maybe_tensor, torch.Tensor):
|
| 129 |
+
return maybe_tensor
|
| 130 |
+
# pyrefly: ignore[bad-return]
|
| 131 |
+
return _wrap_for_grad(maybe_tensor, level)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _wrap_all_tensors(tensor_pytree: _T, level: int) -> _T:
|
| 135 |
+
return tree_map(partial(_wrap_tensor_for_grad, level=level), tensor_pytree)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# TODO: this is more accurate - enable in 3.11
|
| 139 |
+
# _Ts = TypeVarTuple("_Ts")
|
| 140 |
+
# @overload
|
| 141 |
+
# def _as_tuple(val: tuple[*_Ts]) -> tuple[*_Ts]: ...
|
| 142 |
+
@overload
|
| 143 |
+
def _as_tuple(val: tuple[_R, ...]) -> tuple[_R]: ...
|
| 144 |
+
@overload
|
| 145 |
+
def _as_tuple(val: _R) -> tuple[_R]: ...
|
| 146 |
+
def _as_tuple(val: object) -> object:
|
| 147 |
+
if isinstance(val, tuple):
|
| 148 |
+
return val
|
| 149 |
+
return (val,)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# Version of autograd.grad that handles outputs that don't depend on inputs
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _autograd_grad(
|
| 156 |
+
outputs: Sequence[torch.Tensor],
|
| 157 |
+
inputs: Sequence[torch.Tensor],
|
| 158 |
+
grad_outputs: Sequence[torch.Tensor] | None = None,
|
| 159 |
+
retain_graph: bool = False,
|
| 160 |
+
create_graph: bool = True,
|
| 161 |
+
) -> tuple[torch.Tensor, ...]:
|
| 162 |
+
if grad_outputs is None:
|
| 163 |
+
diff_outputs = tuple(out for out in outputs if out.requires_grad)
|
| 164 |
+
else:
|
| 165 |
+
result = tuple(
|
| 166 |
+
(out, go) for out, go in zip(outputs, grad_outputs) if out.requires_grad
|
| 167 |
+
)
|
| 168 |
+
if len(result) == 0:
|
| 169 |
+
diff_outputs, grad_outputs = (), ()
|
| 170 |
+
else:
|
| 171 |
+
diff_outputs, grad_outputs = zip(*result)
|
| 172 |
+
if len(diff_outputs) == 0:
|
| 173 |
+
return tuple(torch.zeros_like(inp) for inp in inputs)
|
| 174 |
+
with torch._dynamo.compiled_autograd._disable():
|
| 175 |
+
grad_inputs = torch.autograd.grad(
|
| 176 |
+
diff_outputs,
|
| 177 |
+
inputs,
|
| 178 |
+
grad_outputs,
|
| 179 |
+
retain_graph=retain_graph,
|
| 180 |
+
create_graph=create_graph,
|
| 181 |
+
allow_unused=True,
|
| 182 |
+
)
|
| 183 |
+
grad_inputs = tuple(
|
| 184 |
+
torch.zeros_like(inp) if gi is None else gi
|
| 185 |
+
for gi, inp in zip(grad_inputs, inputs)
|
| 186 |
+
)
|
| 187 |
+
return grad_inputs
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# NOTE [grad and vjp interaction with no_grad]
|
| 191 |
+
#
|
| 192 |
+
# def f(x):
|
| 193 |
+
# with torch.no_grad():
|
| 194 |
+
# c = x ** 2
|
| 195 |
+
# return x - c
|
| 196 |
+
#
|
| 197 |
+
# The thing to consider is if enable_grad is on/off before grad gets called.
|
| 198 |
+
#
|
| 199 |
+
# Case 1: enable_grad is on.
|
| 200 |
+
# grad(f)(x)
|
| 201 |
+
# In this case, `grad` should respect the inner torch.no_grad.
|
| 202 |
+
#
|
| 203 |
+
# Case 2: enable_grad is off
|
| 204 |
+
# with torch.no_grad():
|
| 205 |
+
# grad(f)(x)
|
| 206 |
+
# In this case, `grad` should respect the inner torch.no_grad, but not the
|
| 207 |
+
# outer one. This is because `grad` is a "function transform": its result
|
| 208 |
+
# should not depend on the result of a context manager outside of `f`.
|
| 209 |
+
#
|
| 210 |
+
# This gives us the following desired behavior:
|
| 211 |
+
# - (nested) grad transforms must obey torch.no_grad inside them
|
| 212 |
+
# - (nested) grad transforms should not obey torch.no_grad outside them
|
| 213 |
+
#
|
| 214 |
+
# To achieve this behavior, upon entering grad/vjp:
|
| 215 |
+
# - we save the current ("previous") is_grad_enabled (*)
|
| 216 |
+
# - we unconditionally enable grad.
|
| 217 |
+
#
|
| 218 |
+
# Inside DynamicLayerBackFallback, when we're temporarily popping `grad` layer
|
| 219 |
+
# off the stack:
|
| 220 |
+
# - if grad_mode is disabled, then we do nothing. (there is a torch.no_grad
|
| 221 |
+
# active, all subsequent grad transforms must obey it).
|
| 222 |
+
# - if grad_mode is enabled, and the previous is_grad_enabled (*) is False,
|
| 223 |
+
# then we temporarily restore the previous `is_grad_enabled`. This is
|
| 224 |
+
# because we're crossing the boundary from a `grad` outside the
|
| 225 |
+
# no_grad to a `grad` inside the no_grad.
|
| 226 |
+
#
|
| 227 |
+
# NB: vjp has some interesting behavior because the vjp's Callable[..., Any] can be called
|
| 228 |
+
# under a different grad_mode than the forward computation...
|
| 229 |
+
#
|
| 230 |
+
# NB: forward-mode AD: forward-mode AD doesn't respect torch.no_grad, but
|
| 231 |
+
# it respects c10::AutoFwGradMode. We've implemented the same logic for
|
| 232 |
+
# our jvp transform (it will have special handling if FwGradMode is disabled).
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# How do we increment and decrement the nesting? I don't think we can.
|
| 236 |
+
@exposed_in("torch.func")
|
| 237 |
+
def vjp(
|
| 238 |
+
func: Callable[..., Any], *primals: Any, has_aux: bool = False
|
| 239 |
+
) -> tuple[Any, Callable[..., Any]] | tuple[Any, Callable[..., Any], Any]:
|
| 240 |
+
"""
|
| 241 |
+
Standing for the vector-Jacobian product, returns a tuple containing the
|
| 242 |
+
results of ``func`` applied to ``primals`` and a function that, when
|
| 243 |
+
given ``cotangents``, computes the reverse-mode Jacobian of ``func`` with
|
| 244 |
+
respect to ``primals`` times ``cotangents``.
|
| 245 |
+
|
| 246 |
+
Args:
|
| 247 |
+
func (Callable[..., Any]): A Python function that takes one or more arguments. Must
|
| 248 |
+
return one or more Tensors.
|
| 249 |
+
primals (Tensors): Positional arguments to ``func`` that must all be
|
| 250 |
+
Tensors. The returned function will also be computing the
|
| 251 |
+
derivative with respect to these arguments
|
| 252 |
+
has_aux (bool): Flag indicating that ``func`` returns a
|
| 253 |
+
``(output, aux)`` tuple where the first element is the output of
|
| 254 |
+
the function to be differentiated and the second element is
|
| 255 |
+
other auxiliary objects that will not be differentiated.
|
| 256 |
+
Default: False.
|
| 257 |
+
|
| 258 |
+
Returns:
|
| 259 |
+
Returns a ``(output, vjp_fn)`` tuple containing the output of ``func``
|
| 260 |
+
applied to ``primals`` and a function that computes the vjp of
|
| 261 |
+
``func`` with respect to all ``primals`` using the cotangents passed
|
| 262 |
+
to the returned function. If ``has_aux is True``, then instead returns a
|
| 263 |
+
``(output, vjp_fn, aux)`` tuple.
|
| 264 |
+
The returned ``vjp_fn`` function will return a tuple of each VJP.
|
| 265 |
+
|
| 266 |
+
When used in simple cases, :func:`vjp` behaves the same as :func:`grad`
|
| 267 |
+
|
| 268 |
+
>>> x = torch.randn([5])
|
| 269 |
+
>>> f = lambda x: x.sin().sum()
|
| 270 |
+
>>> (_, vjpfunc) = torch.func.vjp(f, x)
|
| 271 |
+
>>> grad = vjpfunc(torch.tensor(1.0))[0]
|
| 272 |
+
>>> assert torch.allclose(grad, torch.func.grad(f)(x))
|
| 273 |
+
|
| 274 |
+
However, :func:`vjp` can support functions with multiple outputs by
|
| 275 |
+
passing in the cotangents for each of the outputs
|
| 276 |
+
|
| 277 |
+
>>> x = torch.randn([5])
|
| 278 |
+
>>> f = lambda x: (x.sin(), x.cos())
|
| 279 |
+
>>> (_, vjpfunc) = torch.func.vjp(f, x)
|
| 280 |
+
>>> vjps = vjpfunc((torch.ones([5]), torch.ones([5])))
|
| 281 |
+
>>> assert torch.allclose(vjps[0], x.cos() + -x.sin())
|
| 282 |
+
|
| 283 |
+
:func:`vjp` can even support outputs being Python structs
|
| 284 |
+
|
| 285 |
+
>>> x = torch.randn([5])
|
| 286 |
+
>>> f = lambda x: {"first": x.sin(), "second": x.cos()}
|
| 287 |
+
>>> (_, vjpfunc) = torch.func.vjp(f, x)
|
| 288 |
+
>>> cotangents = {"first": torch.ones([5]), "second": torch.ones([5])}
|
| 289 |
+
>>> vjps = vjpfunc(cotangents)
|
| 290 |
+
>>> assert torch.allclose(vjps[0], x.cos() + -x.sin())
|
| 291 |
+
|
| 292 |
+
The function returned by :func:`vjp` will compute the partials with
|
| 293 |
+
respect to each of the ``primals``
|
| 294 |
+
|
| 295 |
+
>>> x, y = torch.randn([5, 4]), torch.randn([4, 5])
|
| 296 |
+
>>> (_, vjpfunc) = torch.func.vjp(torch.matmul, x, y)
|
| 297 |
+
>>> cotangents = torch.randn([5, 5])
|
| 298 |
+
>>> vjps = vjpfunc(cotangents)
|
| 299 |
+
>>> assert len(vjps) == 2
|
| 300 |
+
>>> assert torch.allclose(vjps[0], torch.matmul(cotangents, y.transpose(0, 1)))
|
| 301 |
+
>>> assert torch.allclose(vjps[1], torch.matmul(x.transpose(0, 1), cotangents))
|
| 302 |
+
|
| 303 |
+
``primals`` are the positional arguments for ``f``. All kwargs use their
|
| 304 |
+
default value
|
| 305 |
+
|
| 306 |
+
>>> x = torch.randn([5])
|
| 307 |
+
>>> def f(x, scale=4.):
|
| 308 |
+
>>> return x * scale
|
| 309 |
+
>>>
|
| 310 |
+
>>> (_, vjpfunc) = torch.func.vjp(f, x)
|
| 311 |
+
>>> vjps = vjpfunc(torch.ones_like(x))
|
| 312 |
+
>>> assert torch.allclose(vjps[0], torch.full(x.shape, 4.0))
|
| 313 |
+
|
| 314 |
+
.. note::
|
| 315 |
+
Using PyTorch ``torch.no_grad`` together with ``vjp``.
|
| 316 |
+
Case 1: Using ``torch.no_grad`` inside a function:
|
| 317 |
+
|
| 318 |
+
>>> def f(x):
|
| 319 |
+
>>> with torch.no_grad():
|
| 320 |
+
>>> c = x ** 2
|
| 321 |
+
>>> return x - c
|
| 322 |
+
|
| 323 |
+
In this case, ``vjp(f)(x)`` will respect the inner ``torch.no_grad``.
|
| 324 |
+
|
| 325 |
+
Case 2: Using ``vjp`` inside ``torch.no_grad`` context manager:
|
| 326 |
+
|
| 327 |
+
>>> # xdoctest: +SKIP(failing)
|
| 328 |
+
>>> with torch.no_grad():
|
| 329 |
+
>>> vjp(f)(x)
|
| 330 |
+
|
| 331 |
+
In this case, ``vjp`` will respect the inner ``torch.no_grad``, but not the
|
| 332 |
+
outer one. This is because ``vjp`` is a "function transform": its result
|
| 333 |
+
should not depend on the result of a context manager outside of ``f``.
|
| 334 |
+
"""
|
| 335 |
+
return _vjp_with_argnums(func, *primals, has_aux=has_aux)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
@contextlib.contextmanager
|
| 339 |
+
def _disable_inference_mode() -> Generator[None, None, None]:
|
| 340 |
+
# Disable inference_mode without clobbering grad_mode / fw_grad_mode.
|
| 341 |
+
# torch.inference_mode(False) unconditionally sets grad_mode=True and
|
| 342 |
+
# fw_grad_mode=True; we save and restore those to avoid that.
|
| 343 |
+
# No-op when inference_mode is already off.
|
| 344 |
+
if not torch.is_inference_mode_enabled():
|
| 345 |
+
yield
|
| 346 |
+
return
|
| 347 |
+
prev_grad = torch.is_grad_enabled()
|
| 348 |
+
prev_fw_grad = torch._C._is_fwd_grad_enabled()
|
| 349 |
+
with torch.inference_mode(False):
|
| 350 |
+
torch._C._set_grad_enabled(prev_grad)
|
| 351 |
+
torch._C._set_fwd_grad_enabled(prev_fw_grad)
|
| 352 |
+
yield
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
@contextlib.contextmanager
|
| 356 |
+
def grad_increment_nesting() -> Generator[int, None, None]:
|
| 357 |
+
try:
|
| 358 |
+
grad_level = _grad_increment_nesting()
|
| 359 |
+
yield grad_level
|
| 360 |
+
finally:
|
| 361 |
+
_grad_decrement_nesting()
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def enter_jvp_nesting() -> int:
|
| 365 |
+
global JVP_NESTING
|
| 366 |
+
jvp_level = _jvp_increment_nesting()
|
| 367 |
+
JVP_NESTING += 1
|
| 368 |
+
return jvp_level
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def exit_jvp_nesting() -> None:
|
| 372 |
+
global JVP_NESTING
|
| 373 |
+
_jvp_decrement_nesting()
|
| 374 |
+
JVP_NESTING -= 1
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@contextlib.contextmanager
|
| 378 |
+
def jvp_increment_nesting() -> Generator[int, None, None]:
|
| 379 |
+
try:
|
| 380 |
+
yield enter_jvp_nesting()
|
| 381 |
+
finally:
|
| 382 |
+
exit_jvp_nesting()
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
@doesnt_support_saved_tensors_hooks
|
| 386 |
+
def _vjp_with_argnums(
|
| 387 |
+
func: Callable[..., Any],
|
| 388 |
+
*primals: Any,
|
| 389 |
+
argnums: argnums_t | None = None,
|
| 390 |
+
has_aux: bool = False,
|
| 391 |
+
) -> tuple[Any, Callable[..., Any]] | tuple[Any, Callable[..., Any], Any]:
|
| 392 |
+
# This is the same function as vjp but also accepts an argnums argument
|
| 393 |
+
# All args are the same as vjp except for the added argument
|
| 394 |
+
# argnums (int or tuple[int,...] | None): Optional, specifies the argument(s) to compute gradients with respect to.
|
| 395 |
+
# If None, computes the gradients with respect to all inputs (used for vjp). Default: None
|
| 396 |
+
#
|
| 397 |
+
# WARN: Users should NOT call this function directly and should just be calling vjp.
|
| 398 |
+
# It is only separated so that inputs passed to jacrev but not differentiated get the correct wrappers.
|
| 399 |
+
#
|
| 400 |
+
# NOTE: All error messages are produced as if vjp was being called, even if this was called by jacrev
|
| 401 |
+
#
|
| 402 |
+
# Returns the same two elements as :func:`vjp` but the function returned, vjp_fn, returns a tuple of VJPs
|
| 403 |
+
# for only the primal elements given by argnums.
|
| 404 |
+
with grad_increment_nesting() as level:
|
| 405 |
+
# See NOTE [grad and vjp interaction with no_grad]
|
| 406 |
+
with torch.enable_grad():
|
| 407 |
+
primals = _wrap_all_tensors(primals, level)
|
| 408 |
+
if argnums is None:
|
| 409 |
+
diff_primals = _create_differentiable(primals, level)
|
| 410 |
+
else:
|
| 411 |
+
diff_primals = _slice_argnums(primals, argnums, as_tuple=False)
|
| 412 |
+
tree_map_(partial(_create_differentiable, level=level), diff_primals)
|
| 413 |
+
primals_out = func(*primals)
|
| 414 |
+
|
| 415 |
+
aux: Any = None
|
| 416 |
+
if has_aux:
|
| 417 |
+
if not (isinstance(primals_out, tuple) and len(primals_out) == 2):
|
| 418 |
+
raise RuntimeError(
|
| 419 |
+
"vjp(f, *primals): output of function f should be a tuple: (output, aux) "
|
| 420 |
+
"if has_aux is True"
|
| 421 |
+
)
|
| 422 |
+
primals_out, aux = primals_out
|
| 423 |
+
aux = _undo_create_differentiable(aux, level)
|
| 424 |
+
|
| 425 |
+
flat_primals_out, primals_out_spec = tree_flatten(primals_out)
|
| 426 |
+
assert_non_empty_tensor_output(flat_primals_out, "vjp(f, *primals)")
|
| 427 |
+
flat_diff_primals, primals_spec = tree_flatten(diff_primals)
|
| 428 |
+
results = _undo_create_differentiable(primals_out, level)
|
| 429 |
+
|
| 430 |
+
for primal_out in flat_primals_out:
|
| 431 |
+
if not isinstance(primal_out, torch.Tensor):
|
| 432 |
+
raise AssertionError(
|
| 433 |
+
f"expected primal_out to be a Tensor, got {type(primal_out)}"
|
| 434 |
+
)
|
| 435 |
+
if primal_out.is_floating_point() or primal_out.is_complex():
|
| 436 |
+
continue
|
| 437 |
+
raise RuntimeError(
|
| 438 |
+
"vjp(f, ...): All outputs of f must be "
|
| 439 |
+
"floating-point or complex Tensors, got Tensor "
|
| 440 |
+
f"with dtype {primal_out.dtype}"
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
def wrapper(
|
| 444 |
+
cotangents: Any,
|
| 445 |
+
retain_graph: bool = True,
|
| 446 |
+
create_graph: bool | None = None,
|
| 447 |
+
) -> Any:
|
| 448 |
+
if create_graph is None:
|
| 449 |
+
create_graph = torch.is_grad_enabled()
|
| 450 |
+
flat_cotangents, cotangents_spec = tree_flatten(cotangents)
|
| 451 |
+
if primals_out_spec != cotangents_spec:
|
| 452 |
+
raise RuntimeError(
|
| 453 |
+
f"Expected pytree structure of cotangents to be the same "
|
| 454 |
+
f"as pytree structure of outputs to the function. "
|
| 455 |
+
f"cotangents: {treespec_pprint(cotangents_spec)}, "
|
| 456 |
+
f"primal output: {treespec_pprint(primals_out_spec)}"
|
| 457 |
+
)
|
| 458 |
+
# This closure runs after grad_increment_nesting exits, so
|
| 459 |
+
# inference_mode may have been restored. Disable it for autograd.
|
| 460 |
+
# Skip under Dynamo — tracing through the generator CM emits
|
| 461 |
+
# spurious _enter_inference_mode nodes.
|
| 462 |
+
ctx = (
|
| 463 |
+
contextlib.nullcontext()
|
| 464 |
+
if torch.compiler.is_compiling()
|
| 465 |
+
else _disable_inference_mode()
|
| 466 |
+
)
|
| 467 |
+
with ctx:
|
| 468 |
+
result = _autograd_grad(
|
| 469 |
+
flat_primals_out,
|
| 470 |
+
flat_diff_primals,
|
| 471 |
+
flat_cotangents,
|
| 472 |
+
retain_graph=retain_graph,
|
| 473 |
+
create_graph=create_graph,
|
| 474 |
+
)
|
| 475 |
+
return tree_unflatten(result, primals_spec)
|
| 476 |
+
|
| 477 |
+
if has_aux:
|
| 478 |
+
return results, wrapper, aux # type: ignore[possibly-unbound]
|
| 479 |
+
else:
|
| 480 |
+
return results, wrapper
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def _safe_zero_index(x: tuple[_R, ...]) -> _R:
|
| 484 |
+
if len(x) != 1:
|
| 485 |
+
raise AssertionError(f"expected tuple of length 1, got length {len(x)}")
|
| 486 |
+
return x[0]
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
# jacrev and jacfwd don't support complex functions
|
| 490 |
+
# Helper function to throw appropriate error.
|
| 491 |
+
def error_if_complex(func_name: str, args: Any, is_input: bool) -> None:
|
| 492 |
+
flat_args = pytree.tree_leaves(args)
|
| 493 |
+
for idx, arg in enumerate(flat_args):
|
| 494 |
+
if isinstance(arg, torch.Tensor) and arg.dtype.is_complex:
|
| 495 |
+
input_or_output = "inputs" if is_input else "outputs"
|
| 496 |
+
err_msg = (
|
| 497 |
+
f"{func_name}: Expected all {input_or_output} "
|
| 498 |
+
f"to be real but received complex tensor at flattened input idx: {idx}"
|
| 499 |
+
)
|
| 500 |
+
raise RuntimeError(err_msg)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
@exposed_in("torch.func")
|
| 504 |
+
def jacrev(
|
| 505 |
+
func: Callable[..., Any],
|
| 506 |
+
argnums: int | tuple[int, ...] = 0,
|
| 507 |
+
*,
|
| 508 |
+
has_aux: bool = False,
|
| 509 |
+
chunk_size: int | None = None,
|
| 510 |
+
_preallocate_and_copy: bool = False,
|
| 511 |
+
) -> Callable[..., Any]:
|
| 512 |
+
"""
|
| 513 |
+
Computes the Jacobian of ``func`` with respect to the arg(s) at index
|
| 514 |
+
``argnum`` using reverse mode autodiff
|
| 515 |
+
|
| 516 |
+
.. note::
|
| 517 |
+
Using :attr:`chunk_size=1` is equivalent to computing the jacobian
|
| 518 |
+
row-by-row with a for-loop i.e. the constraints of :func:`vmap` are
|
| 519 |
+
not applicable.
|
| 520 |
+
|
| 521 |
+
Args:
|
| 522 |
+
func (function): A Python function that takes one or more arguments,
|
| 523 |
+
one of which must be a Tensor, and returns one or more Tensors
|
| 524 |
+
argnums (int or tuple[int, ...]): Optional, integer or tuple of integers,
|
| 525 |
+
saying which arguments to get the Jacobian with respect to.
|
| 526 |
+
Default: 0.
|
| 527 |
+
has_aux (bool): Flag indicating that ``func`` returns a
|
| 528 |
+
``(output, aux)`` tuple where the first element is the output of
|
| 529 |
+
the function to be differentiated and the second element is
|
| 530 |
+
auxiliary objects that will not be differentiated.
|
| 531 |
+
Default: False.
|
| 532 |
+
chunk_size (None or int): If None (default), use the maximum chunk size
|
| 533 |
+
(equivalent to doing a single vmap over vjp to compute the jacobian).
|
| 534 |
+
If 1, then compute the jacobian row-by-row with a for-loop.
|
| 535 |
+
If not None, then compute the jacobian :attr:`chunk_size` rows at a time
|
| 536 |
+
(equivalent to doing multiple vmap over vjp). If you run into memory issues computing
|
| 537 |
+
the jacobian, please try to specify a non-None chunk_size.
|
| 538 |
+
|
| 539 |
+
Returns:
|
| 540 |
+
Returns a function that takes in the same inputs as ``func`` and
|
| 541 |
+
returns the Jacobian of ``func`` with respect to the arg(s) at
|
| 542 |
+
``argnums``. If ``has_aux is True``, then the returned function
|
| 543 |
+
instead returns a ``(jacobian, aux)`` tuple where ``jacobian``
|
| 544 |
+
is the Jacobian and ``aux`` is auxiliary objects returned by ``func``.
|
| 545 |
+
|
| 546 |
+
A basic usage with a pointwise, unary operation will give a diagonal array
|
| 547 |
+
as the Jacobian
|
| 548 |
+
|
| 549 |
+
>>> from torch.func import jacrev
|
| 550 |
+
>>> x = torch.randn(5)
|
| 551 |
+
>>> jacobian = jacrev(torch.sin)(x)
|
| 552 |
+
>>> expected = torch.diag(torch.cos(x))
|
| 553 |
+
>>> assert torch.allclose(jacobian, expected)
|
| 554 |
+
|
| 555 |
+
If you would like to compute the output of the function as well as the
|
| 556 |
+
jacobian of the function, use the ``has_aux`` flag to return the output
|
| 557 |
+
as an auxiliary object:
|
| 558 |
+
|
| 559 |
+
>>> from torch.func import jacrev
|
| 560 |
+
>>> x = torch.randn(5)
|
| 561 |
+
>>>
|
| 562 |
+
>>> def f(x):
|
| 563 |
+
>>> return x.sin()
|
| 564 |
+
>>>
|
| 565 |
+
>>> def g(x):
|
| 566 |
+
>>> result = f(x)
|
| 567 |
+
>>> return result, result
|
| 568 |
+
>>>
|
| 569 |
+
>>> jacobian_f, f_x = jacrev(g, has_aux=True)(x)
|
| 570 |
+
>>> assert torch.allclose(f_x, f(x))
|
| 571 |
+
|
| 572 |
+
:func:`jacrev` can be composed with vmap to produce batched
|
| 573 |
+
Jacobians:
|
| 574 |
+
|
| 575 |
+
>>> from torch.func import jacrev, vmap
|
| 576 |
+
>>> x = torch.randn(64, 5)
|
| 577 |
+
>>> jacobian = vmap(jacrev(torch.sin))(x)
|
| 578 |
+
>>> assert jacobian.shape == (64, 5, 5)
|
| 579 |
+
|
| 580 |
+
Additionally, :func:`jacrev` can be composed with itself to produce
|
| 581 |
+
Hessians
|
| 582 |
+
|
| 583 |
+
>>> from torch.func import jacrev
|
| 584 |
+
>>> def f(x):
|
| 585 |
+
>>> return x.sin().sum()
|
| 586 |
+
>>>
|
| 587 |
+
>>> x = torch.randn(5)
|
| 588 |
+
>>> hessian = jacrev(jacrev(f))(x)
|
| 589 |
+
>>> assert torch.allclose(hessian, torch.diag(-x.sin()))
|
| 590 |
+
|
| 591 |
+
By default, :func:`jacrev` computes the Jacobian with respect to the first
|
| 592 |
+
input. However, it can compute the Jacboian with respect to a different
|
| 593 |
+
argument by using ``argnums``:
|
| 594 |
+
|
| 595 |
+
>>> from torch.func import jacrev
|
| 596 |
+
>>> def f(x, y):
|
| 597 |
+
>>> return x + y ** 2
|
| 598 |
+
>>>
|
| 599 |
+
>>> x, y = torch.randn(5), torch.randn(5)
|
| 600 |
+
>>> jacobian = jacrev(f, argnums=1)(x, y)
|
| 601 |
+
>>> expected = torch.diag(2 * y)
|
| 602 |
+
>>> assert torch.allclose(jacobian, expected)
|
| 603 |
+
|
| 604 |
+
Additionally, passing a tuple to ``argnums`` will compute the Jacobian
|
| 605 |
+
with respect to multiple arguments
|
| 606 |
+
|
| 607 |
+
>>> from torch.func import jacrev
|
| 608 |
+
>>> def f(x, y):
|
| 609 |
+
>>> return x + y ** 2
|
| 610 |
+
>>>
|
| 611 |
+
>>> x, y = torch.randn(5), torch.randn(5)
|
| 612 |
+
>>> jacobian = jacrev(f, argnums=(0, 1))(x, y)
|
| 613 |
+
>>> expectedX = torch.diag(torch.ones_like(x))
|
| 614 |
+
>>> expectedY = torch.diag(2 * y)
|
| 615 |
+
>>> assert torch.allclose(jacobian[0], expectedX)
|
| 616 |
+
>>> assert torch.allclose(jacobian[1], expectedY)
|
| 617 |
+
|
| 618 |
+
.. note::
|
| 619 |
+
Using PyTorch ``torch.no_grad`` together with ``jacrev``.
|
| 620 |
+
Case 1: Using ``torch.no_grad`` inside a function:
|
| 621 |
+
|
| 622 |
+
>>> def f(x):
|
| 623 |
+
>>> with torch.no_grad():
|
| 624 |
+
>>> c = x ** 2
|
| 625 |
+
>>> return x - c
|
| 626 |
+
|
| 627 |
+
In this case, ``jacrev(f)(x)`` will respect the inner ``torch.no_grad``.
|
| 628 |
+
|
| 629 |
+
Case 2: Using ``jacrev`` inside ``torch.no_grad`` context manager:
|
| 630 |
+
|
| 631 |
+
>>> with torch.no_grad():
|
| 632 |
+
>>> jacrev(f)(x)
|
| 633 |
+
|
| 634 |
+
In this case, ``jacrev`` will respect the inner ``torch.no_grad``, but not the
|
| 635 |
+
outer one. This is because ``jacrev`` is a "function transform": its result
|
| 636 |
+
should not depend on the result of a context manager outside of ``f``.
|
| 637 |
+
"""
|
| 638 |
+
if not (chunk_size is None or chunk_size > 0):
|
| 639 |
+
raise ValueError("jacrev: `chunk_size` should be greater than 0.")
|
| 640 |
+
|
| 641 |
+
@wraps(func)
|
| 642 |
+
def wrapper_fn(*args: Any) -> Any:
|
| 643 |
+
error_if_complex("jacrev", args, is_input=True)
|
| 644 |
+
vjp_out = _vjp_with_argnums(func, *args, argnums=argnums, has_aux=has_aux)
|
| 645 |
+
aux: Any = None
|
| 646 |
+
if has_aux:
|
| 647 |
+
# pyrefly: ignore[bad-unpacking]
|
| 648 |
+
output, vjp_fn, aux = vjp_out
|
| 649 |
+
else:
|
| 650 |
+
# pyrefly: ignore[bad-unpacking]
|
| 651 |
+
output, vjp_fn = vjp_out
|
| 652 |
+
|
| 653 |
+
# See NOTE: [Computing jacobian with vmap and vjp for multiple outputs]
|
| 654 |
+
flat_output, output_spec = tree_flatten(output)
|
| 655 |
+
|
| 656 |
+
error_if_complex("jacrev", flat_output, is_input=False)
|
| 657 |
+
|
| 658 |
+
# NB: vjp already checks that all outputs are tensors
|
| 659 |
+
# Step 1: Construct grad_outputs by splitting the standard basis
|
| 660 |
+
flat_output_numels = tuple(out.numel() for out in flat_output)
|
| 661 |
+
|
| 662 |
+
primals = _slice_argnums(args, argnums)
|
| 663 |
+
flat_primals, primals_spec = tree_flatten(primals)
|
| 664 |
+
|
| 665 |
+
def compute_jacobian_stacked() -> list[Any]:
|
| 666 |
+
# Helper function to compute chunked Jacobian
|
| 667 |
+
# The intermediate chunked calculation are only
|
| 668 |
+
# scoped at this function level.
|
| 669 |
+
chunked_results: list[list[Any]] = []
|
| 670 |
+
for flat_basis_chunk in _chunked_standard_basis_for_(
|
| 671 |
+
flat_output, flat_output_numels, chunk_size=chunk_size
|
| 672 |
+
):
|
| 673 |
+
if chunk_size == 1:
|
| 674 |
+
# sanity check.
|
| 675 |
+
for t in flat_basis_chunk:
|
| 676 |
+
if t.size(0) != 1:
|
| 677 |
+
raise AssertionError(
|
| 678 |
+
f"expected t.size(0) to be 1, got {t.size(0)}"
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
flat_basis_chunk = tree_map(
|
| 682 |
+
lambda t: torch.squeeze(t, 0), flat_basis_chunk
|
| 683 |
+
)
|
| 684 |
+
|
| 685 |
+
basis = tree_unflatten(flat_basis_chunk, output_spec)
|
| 686 |
+
|
| 687 |
+
if chunk_size == 1:
|
| 688 |
+
# Behaviour with `chunk_size=1` is same as `for-loop`
|
| 689 |
+
# i.e. user shouldn't deal with the limitations of vmap.
|
| 690 |
+
chunked_result = vjp_fn(basis)
|
| 691 |
+
else: # chunk_size is None or chunk_size != 1
|
| 692 |
+
chunked_result = vmap(vjp_fn)(basis)
|
| 693 |
+
|
| 694 |
+
flat_results = pytree.tree_leaves(chunked_result)
|
| 695 |
+
|
| 696 |
+
if chunk_size == 1:
|
| 697 |
+
flat_results = tree_map(
|
| 698 |
+
lambda t: torch.unsqueeze(t, 0), flat_results
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
chunked_results.append(flat_results)
|
| 702 |
+
|
| 703 |
+
if len(chunked_results) == 1:
|
| 704 |
+
# Short-circuit if we used a single chunk
|
| 705 |
+
return chunked_results[0]
|
| 706 |
+
|
| 707 |
+
# Concatenate chunks.
|
| 708 |
+
flat_results = []
|
| 709 |
+
# Iterate and concat the jacobians of different
|
| 710 |
+
# inputs.
|
| 711 |
+
for idx in range(len(flat_primals)):
|
| 712 |
+
r = tuple(r_[idx] for r_ in chunked_results)
|
| 713 |
+
flat_results.append(torch.cat(r, 0))
|
| 714 |
+
|
| 715 |
+
return flat_results
|
| 716 |
+
|
| 717 |
+
def compute_jacobian_preallocate_and_copy() -> list[Any]:
|
| 718 |
+
# Helper function to compute chunked Jacobian
|
| 719 |
+
# The intermediate chunked calculation are only
|
| 720 |
+
# scoped at this function level.
|
| 721 |
+
out_vec_size = sum(flat_output_numels)
|
| 722 |
+
|
| 723 |
+
# Don't pre-allocate if we have a single chunk.
|
| 724 |
+
stacked_results: list[torch.Tensor] = []
|
| 725 |
+
if not (chunk_size is None or chunk_size >= out_vec_size):
|
| 726 |
+
stacked_results = [
|
| 727 |
+
primal.new_zeros(out_vec_size, *primal.shape)
|
| 728 |
+
for primal in flat_primals
|
| 729 |
+
]
|
| 730 |
+
|
| 731 |
+
for idx, flat_basis_chunk in enumerate(
|
| 732 |
+
_chunked_standard_basis_for_(
|
| 733 |
+
flat_output, flat_output_numels, chunk_size=chunk_size
|
| 734 |
+
)
|
| 735 |
+
):
|
| 736 |
+
if chunk_size == 1:
|
| 737 |
+
# sanity check.
|
| 738 |
+
for t in flat_basis_chunk:
|
| 739 |
+
if t.size(0) != 1:
|
| 740 |
+
raise AssertionError(
|
| 741 |
+
f"expected t.size(0) to be 1, got {t.size(0)}"
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
flat_basis_chunk = [torch.squeeze(t, 0) for t in flat_basis_chunk]
|
| 745 |
+
|
| 746 |
+
basis = tree_unflatten(flat_basis_chunk, output_spec)
|
| 747 |
+
|
| 748 |
+
if chunk_size == 1:
|
| 749 |
+
# Behaviour with `chunk_size=1` is same as `for-loop`
|
| 750 |
+
# i.e. user shouldn't deal with the limitations of vmap.
|
| 751 |
+
chunked_result = vjp_fn(basis)
|
| 752 |
+
else: # chunk_size is None or chunk_size != 1
|
| 753 |
+
chunked_result = vmap(vjp_fn)(basis)
|
| 754 |
+
|
| 755 |
+
flat_results = pytree.tree_leaves(chunked_result)
|
| 756 |
+
|
| 757 |
+
# Short-circuit if we have a single chunk.
|
| 758 |
+
if chunk_size is None or chunk_size >= out_vec_size:
|
| 759 |
+
if chunk_size == 1: # and out_vec_size == 1
|
| 760 |
+
# Since we squeezed the output dim
|
| 761 |
+
flat_results = tree_map(
|
| 762 |
+
lambda t: torch.unsqueeze(t, 0), flat_results
|
| 763 |
+
)
|
| 764 |
+
return flat_results
|
| 765 |
+
|
| 766 |
+
for r, sr in zip(flat_results, stacked_results): # type: ignore[possibly-unbound]
|
| 767 |
+
sr[idx * chunk_size : (idx + 1) * chunk_size].copy_(r)
|
| 768 |
+
|
| 769 |
+
return stacked_results # type: ignore[possibly-unbound]
|
| 770 |
+
|
| 771 |
+
if _preallocate_and_copy:
|
| 772 |
+
flat_jacobians_per_input = compute_jacobian_preallocate_and_copy()
|
| 773 |
+
else:
|
| 774 |
+
flat_jacobians_per_input = compute_jacobian_stacked()
|
| 775 |
+
|
| 776 |
+
# Step 2: The returned jacobian is one big tensor per input. In this step,
|
| 777 |
+
# we split each Tensor by output.
|
| 778 |
+
flat_jacobians_per_input = [
|
| 779 |
+
result.split(flat_output_numels, dim=0)
|
| 780 |
+
for result in flat_jacobians_per_input
|
| 781 |
+
]
|
| 782 |
+
flat_input_flat_output = [
|
| 783 |
+
tuple(
|
| 784 |
+
split.view(out.shape + primal.shape)
|
| 785 |
+
for split, out in zip(splits, flat_output)
|
| 786 |
+
)
|
| 787 |
+
for splits, primal in zip(flat_jacobians_per_input, flat_primals)
|
| 788 |
+
]
|
| 789 |
+
|
| 790 |
+
# Step 3: Right now, `jacobian` is a List[List[Tensor]].
|
| 791 |
+
# The outer List corresponds to the number of primals,
|
| 792 |
+
# the inner List corresponds to the number of outputs.
|
| 793 |
+
# We need to:
|
| 794 |
+
# a. Exchange the order of the outer List and inner List
|
| 795 |
+
# b. tree_unflatten the inner Lists (which correspond to the primals)
|
| 796 |
+
# c. handle the argnums=int case
|
| 797 |
+
# d. tree_unflatten the outer List (which corresponds to the outputs)
|
| 798 |
+
flat_output_flat_input = tuple(zip(*flat_input_flat_output))
|
| 799 |
+
|
| 800 |
+
flat_output_input = tuple(
|
| 801 |
+
tree_unflatten(flat_input, primals_spec)
|
| 802 |
+
for flat_input in flat_output_flat_input
|
| 803 |
+
)
|
| 804 |
+
|
| 805 |
+
if isinstance(argnums, int):
|
| 806 |
+
flat_output_input = tuple(
|
| 807 |
+
_safe_zero_index(flat_input) for flat_input in flat_output_input
|
| 808 |
+
)
|
| 809 |
+
output_input = tree_unflatten(flat_output_input, output_spec)
|
| 810 |
+
if has_aux:
|
| 811 |
+
return output_input, aux # type: ignore[possibly-unbound]
|
| 812 |
+
return output_input
|
| 813 |
+
|
| 814 |
+
return wrapper_fn
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
# NOTE: [Computing jacobian with vmap and vjp for multiple outputs]
|
| 818 |
+
#
|
| 819 |
+
# Let's consider f(x) = (x**2, x.sum()) and let x = torch.randn(3).
|
| 820 |
+
# It turns out we can compute the jacobian of this function with a single
|
| 821 |
+
# call to autograd.grad by using vmap over the correct grad_outputs.
|
| 822 |
+
#
|
| 823 |
+
# Firstly, one way to compute the jacobian is to stack x**2 and x.sum()
|
| 824 |
+
# into a 4D vector. E.g., use g(x) = torch.stack([x**2, x.sum()])
|
| 825 |
+
#
|
| 826 |
+
# To get the first row of the jacobian, we call
|
| 827 |
+
# >>> autograd.grad(g(x), x, grad_outputs=torch.tensor([1, 0, 0, 0]))
|
| 828 |
+
# To get the 2nd row of the jacobian, we call
|
| 829 |
+
# >>> autograd.grad(g(x), x, grad_outputs=torch.tensor([0, 1, 0, 0]))
|
| 830 |
+
# and so on.
|
| 831 |
+
#
|
| 832 |
+
# Using vmap, we can vectorize all 4 of these computations into one by
|
| 833 |
+
# passing the standard basis for R^4 as the grad_output.
|
| 834 |
+
# vmap(partial(autograd.grad, g(x), x))(torch.eye(4)).
|
| 835 |
+
#
|
| 836 |
+
# Now, how do we compute the jacobian *without stacking the output*?
|
| 837 |
+
# We can just split the standard basis across the outputs. So to
|
| 838 |
+
# compute the jacobian of f(x), we'd use
|
| 839 |
+
# >>> autograd.grad(f(x), x, grad_outputs=_construct_standard_basis_for(...))
|
| 840 |
+
# The grad_outputs looks like the following:
|
| 841 |
+
# ( torch.tensor([[1, 0, 0],
|
| 842 |
+
# [0, 1, 0],
|
| 843 |
+
# [0, 0, 1],
|
| 844 |
+
# [0, 0, 0]]),
|
| 845 |
+
# torch.tensor([[0],
|
| 846 |
+
# [0],
|
| 847 |
+
# [0],
|
| 848 |
+
# [1]]) )
|
| 849 |
+
#
|
| 850 |
+
# But we're not done yet!
|
| 851 |
+
# >>> vmap(partial(autograd.grad(f(x), x, grad_outputs=...)))
|
| 852 |
+
# returns a Tensor of shape [4, 3]. We have to remember to split the
|
| 853 |
+
# jacobian of shape [4, 3] into two:
|
| 854 |
+
# - one of shape [3, 3] for the first output
|
| 855 |
+
# - one of shape [ 3] for the second output
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
def _chunked_standard_basis_for_(
|
| 859 |
+
tensors: Sequence[torch.Tensor],
|
| 860 |
+
tensor_numels: Sequence[int],
|
| 861 |
+
chunk_size: int | None = None,
|
| 862 |
+
) -> Generator[tuple[torch.Tensor, ...], None, None]:
|
| 863 |
+
# This function:
|
| 864 |
+
# - constructs a N=sum(tensor_numels) standard basis. i.e. an NxN identity matrix.
|
| 865 |
+
# - Splits the identity matrix into chunks with each chunk size determined by `tensor_numels`.
|
| 866 |
+
# - Each chunk corresponds to one tensor. The chunk has the same dtype and
|
| 867 |
+
# device as the tensor
|
| 868 |
+
#
|
| 869 |
+
# For example, with tensor_numels = [1, 2, 1], this function returns:
|
| 870 |
+
# ( tensor([[1], tensor([[0, 0], tensor([[0],
|
| 871 |
+
# [0], [1, 0], [0],
|
| 872 |
+
# [0], [0, 1], [0],
|
| 873 |
+
# [0]]) , [0, 0]]) , [1]]) )
|
| 874 |
+
#
|
| 875 |
+
# Precondition: tensor_numels == tuple(tensor.numel() for tensor in tensors)
|
| 876 |
+
# Precondition: tensors always has at least one element.
|
| 877 |
+
#
|
| 878 |
+
# See NOTE: [Computing jacobian with vmap and grad for multiple tensors]
|
| 879 |
+
# for context behind this function.
|
| 880 |
+
# NOTE: Argument `chunk_size` is used to generate chunked basis instead of
|
| 881 |
+
# one huge basis matrix. `chunk_size` dictates the maximum size of the
|
| 882 |
+
# basis matrix along dim=0.
|
| 883 |
+
if len(tensors) != len(tensor_numels):
|
| 884 |
+
raise AssertionError(
|
| 885 |
+
f"len(tensors)={len(tensors)} != len(tensor_numels)={len(tensor_numels)}"
|
| 886 |
+
)
|
| 887 |
+
if len(tensors) == 0:
|
| 888 |
+
raise AssertionError("tensors must have at least one element")
|
| 889 |
+
if chunk_size is not None and chunk_size <= 0:
|
| 890 |
+
raise AssertionError(f"chunk_size must be > 0 or None, got {chunk_size}")
|
| 891 |
+
total_numel = sum(tensor_numels)
|
| 892 |
+
if chunk_size and chunk_size < total_numel:
|
| 893 |
+
chunk_numels = get_chunk_sizes(total_numel, chunk_size)
|
| 894 |
+
else: # chunk_size is None or chunk_size >= total_numel
|
| 895 |
+
chunk_size = total_numel
|
| 896 |
+
chunk_numels = [total_numel]
|
| 897 |
+
|
| 898 |
+
diag_start_indices = (
|
| 899 |
+
0,
|
| 900 |
+
*torch.tensor(tensor_numels).cumsum(dim=0)[:-1].neg().unbind(),
|
| 901 |
+
)
|
| 902 |
+
|
| 903 |
+
for chunk_idx, total_numel in enumerate(chunk_numels):
|
| 904 |
+
chunks = tuple(
|
| 905 |
+
tensor.new_zeros(total_numel, tensor_numel)
|
| 906 |
+
for tensor, tensor_numel in zip(tensors, tensor_numels)
|
| 907 |
+
)
|
| 908 |
+
|
| 909 |
+
for chunk, diag_start_idx in zip(chunks, diag_start_indices):
|
| 910 |
+
offset = int(diag_start_idx) + chunk_idx * chunk_size
|
| 911 |
+
chunk.diagonal(offset).fill_(1)
|
| 912 |
+
chunks = tuple(
|
| 913 |
+
chunk.view(total_numel, *tensor.shape)
|
| 914 |
+
for chunk, tensor in zip(chunks, tensors)
|
| 915 |
+
)
|
| 916 |
+
yield chunks
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
def _construct_standard_basis_for(
|
| 920 |
+
tensors: Sequence[torch.Tensor], tensor_numels: Sequence[int]
|
| 921 |
+
) -> tuple[torch.Tensor, ...] | None:
|
| 922 |
+
for basis in _chunked_standard_basis_for_(tensors, tensor_numels, chunk_size=None):
|
| 923 |
+
return basis
|
| 924 |
+
return None
|
| 925 |
+
|
| 926 |
+
|
| 927 |
+
def _validate_and_wrap_argnum(argnum: int, num_args: int) -> int:
|
| 928 |
+
if not isinstance(argnum, int):
|
| 929 |
+
raise RuntimeError(f"argnum must be int, got: {type(argnum)}")
|
| 930 |
+
if argnum >= 0 and argnum < num_args:
|
| 931 |
+
return argnum
|
| 932 |
+
if argnum < 0 and argnum >= -num_args:
|
| 933 |
+
return argnum + num_args
|
| 934 |
+
raise RuntimeError(f"Got argnum={argnum}, but only {num_args} positional inputs")
|
| 935 |
+
|
| 936 |
+
|
| 937 |
+
def _check_unique_non_empty(argnums: argnums_t) -> None:
|
| 938 |
+
if isinstance(argnums, tuple):
|
| 939 |
+
if len(argnums) == 0:
|
| 940 |
+
raise RuntimeError("argnums must be non-empty")
|
| 941 |
+
if len(set(argnums)) != len(argnums):
|
| 942 |
+
raise RuntimeError(f"argnums elements must be unique, got {argnums}")
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
def _replace_args(
|
| 946 |
+
old_args: tuple[Any, ...], new_args: tuple[Any, ...], argnums: argnums_t
|
| 947 |
+
) -> tuple[Any, ...]:
|
| 948 |
+
if isinstance(argnums, int):
|
| 949 |
+
if len(new_args) != 1:
|
| 950 |
+
raise RuntimeError(
|
| 951 |
+
f"new_args should be of size 1, was of size {len(new_args)}"
|
| 952 |
+
)
|
| 953 |
+
return tuple(
|
| 954 |
+
new_args[0] if i == argnums else old_args[i] for i in range(len(old_args))
|
| 955 |
+
)
|
| 956 |
+
if isinstance(argnums, tuple):
|
| 957 |
+
if len(new_args) != len(argnums):
|
| 958 |
+
raise RuntimeError(
|
| 959 |
+
"new_args should have the same size as argnums. "
|
| 960 |
+
f"Argnums size {len(argnums)}, new_args size {len(new_args)}"
|
| 961 |
+
)
|
| 962 |
+
|
| 963 |
+
argnums_tuple = argnums
|
| 964 |
+
|
| 965 |
+
def get_right_elem(i: int) -> Any:
|
| 966 |
+
return (
|
| 967 |
+
new_args[argnums_tuple.index(i)] if i in argnums_tuple else old_args[i]
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
return tuple(get_right_elem(i) for i in range(len(old_args)))
|
| 971 |
+
raise RuntimeError(f"argnums must be int or Tuple[int, ...], got: {type(argnums)}")
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
def _validate_and_wrap_argnums(argnums: argnums_t, num_args: int) -> argnums_t:
|
| 975 |
+
if isinstance(argnums, int):
|
| 976 |
+
return _validate_and_wrap_argnum(argnums, num_args)
|
| 977 |
+
if isinstance(argnums, tuple):
|
| 978 |
+
return tuple(_validate_and_wrap_argnum(argnum, num_args) for argnum in argnums)
|
| 979 |
+
raise AssertionError("Should never get here")
|
| 980 |
+
|
| 981 |
+
|
| 982 |
+
def _slice_argnums(
|
| 983 |
+
args: tuple[Any, ...], argnums: argnums_t, as_tuple: bool = True
|
| 984 |
+
) -> Any:
|
| 985 |
+
if not isinstance(argnums, int) and not isinstance(argnums, tuple):
|
| 986 |
+
raise RuntimeError(
|
| 987 |
+
f"argnums must be int or Tuple[int, ...], got: {type(argnums)}"
|
| 988 |
+
)
|
| 989 |
+
argnums = _validate_and_wrap_argnums(argnums, len(args))
|
| 990 |
+
_check_unique_non_empty(argnums)
|
| 991 |
+
if isinstance(argnums, int):
|
| 992 |
+
if as_tuple:
|
| 993 |
+
return (args[argnums],)
|
| 994 |
+
else:
|
| 995 |
+
return args[argnums]
|
| 996 |
+
return tuple(args[i] for i in argnums)
|
| 997 |
+
|
| 998 |
+
|
| 999 |
+
JVP_NESTING = 0
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
def assert_flat_tuple_of_tensors(elts: Any, api: str, argname: str) -> None:
|
| 1003 |
+
if not isinstance(elts, tuple):
|
| 1004 |
+
raise RuntimeError(
|
| 1005 |
+
f"{api}: Expected {argname} to be a tuple of Tensors, got {type(elts)}"
|
| 1006 |
+
)
|
| 1007 |
+
for elt in elts:
|
| 1008 |
+
if isinstance(elt, torch.Tensor):
|
| 1009 |
+
continue
|
| 1010 |
+
raise RuntimeError(
|
| 1011 |
+
f"{api}: Expected {argname} to be a tuple of Tensors, got "
|
| 1012 |
+
f"a tuple with an element of type {type(elt)}"
|
| 1013 |
+
)
|
| 1014 |
+
if len(elts) == 0:
|
| 1015 |
+
raise RuntimeError(
|
| 1016 |
+
f"{api}: Expected {argname} to be a non-empty tuple of Tensors."
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
def assert_non_empty_tensor_output(output: list[Any], api: str) -> None:
|
| 1021 |
+
if (len(output) == 1 and output[0] is None) or len(output) < 1:
|
| 1022 |
+
raise RuntimeError(
|
| 1023 |
+
f"{api}: Expected f to be a function that has non-empty output (got output = {output})"
|
| 1024 |
+
)
|
| 1025 |
+
for o in output:
|
| 1026 |
+
if not isinstance(o, torch.Tensor):
|
| 1027 |
+
raise RuntimeError(
|
| 1028 |
+
f"{api}: expected f(*primals) to return only tensors"
|
| 1029 |
+
f", got unsupported type {type(o)}"
|
| 1030 |
+
)
|
| 1031 |
+
|
| 1032 |
+
|
| 1033 |
+
def assert_output_is_tensor_or_tensors(output: Any, api: str) -> None:
|
| 1034 |
+
if isinstance(output, torch.Tensor):
|
| 1035 |
+
return
|
| 1036 |
+
if not isinstance(output, tuple):
|
| 1037 |
+
raise RuntimeError(
|
| 1038 |
+
f"{api}: Expected output of f to be a Tensor or Tensors, got {type(output)}"
|
| 1039 |
+
)
|
| 1040 |
+
if len(output) == 0:
|
| 1041 |
+
raise RuntimeError(
|
| 1042 |
+
f"{api}: Expected output of f to be a non-empty tuple of Tensors."
|
| 1043 |
+
)
|
| 1044 |
+
for out in output:
|
| 1045 |
+
if isinstance(out, torch.Tensor):
|
| 1046 |
+
continue
|
| 1047 |
+
raise RuntimeError(
|
| 1048 |
+
f"{api}: Expected output of f to be a Tensor or Tensors, got "
|
| 1049 |
+
f"{type(out)} as an output"
|
| 1050 |
+
)
|
| 1051 |
+
|
| 1052 |
+
|
| 1053 |
+
def assert_non_empty_list_of_tensors(
|
| 1054 |
+
output: list[torch.Tensor], api: str, argname: str
|
| 1055 |
+
) -> None:
|
| 1056 |
+
if len(output) == 0:
|
| 1057 |
+
raise RuntimeError(f"{api}: Expected {argname} to contain at least one Tensor.")
|
| 1058 |
+
for out in output:
|
| 1059 |
+
if isinstance(out, torch.Tensor):
|
| 1060 |
+
continue
|
| 1061 |
+
raise RuntimeError(
|
| 1062 |
+
f"{api}: Expected {argname} to only contain Tensors, got {type(out)}"
|
| 1063 |
+
)
|
| 1064 |
+
|
| 1065 |
+
|
| 1066 |
+
jvp_str = "jvp(f, primals, tangents)"
|
| 1067 |
+
|
| 1068 |
+
|
| 1069 |
+
def safe_unpack_dual(
|
| 1070 |
+
dual: torch.Tensor, strict: bool
|
| 1071 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1072 |
+
if not isinstance(dual, torch.Tensor):
|
| 1073 |
+
raise RuntimeError(
|
| 1074 |
+
f"{jvp_str}: expected f(*args) to return only tensors"
|
| 1075 |
+
f", got unsupported type {type(dual)}"
|
| 1076 |
+
)
|
| 1077 |
+
|
| 1078 |
+
primal, tangent = fwAD.unpack_dual(dual)
|
| 1079 |
+
if tangent is None:
|
| 1080 |
+
if strict:
|
| 1081 |
+
raise RuntimeError(
|
| 1082 |
+
"jvp(f, primals, tangents, strict=True): "
|
| 1083 |
+
"The output of f is independent of "
|
| 1084 |
+
"the inputs. This is not allowed with strict=True."
|
| 1085 |
+
)
|
| 1086 |
+
tangent = torch.zeros_like(primal)
|
| 1087 |
+
return primal, tangent
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
@exposed_in("torch.func")
|
| 1091 |
+
def jvp(
|
| 1092 |
+
func: Callable[..., Any],
|
| 1093 |
+
primals: Any,
|
| 1094 |
+
tangents: Any,
|
| 1095 |
+
*,
|
| 1096 |
+
strict: bool = False,
|
| 1097 |
+
has_aux: bool = False,
|
| 1098 |
+
) -> tuple[Any, Any] | tuple[Any, Any, Any]:
|
| 1099 |
+
"""
|
| 1100 |
+
Standing for the Jacobian-vector product, returns a tuple containing
|
| 1101 |
+
the output of `func(*primals)` and the "Jacobian of ``func`` evaluated at
|
| 1102 |
+
``primals``" times ``tangents``. This is also known as forward-mode autodiff.
|
| 1103 |
+
|
| 1104 |
+
Args:
|
| 1105 |
+
func (function): A Python function that takes one or more arguments,
|
| 1106 |
+
one of which must be a Tensor, and returns one or more Tensors
|
| 1107 |
+
primals (Tensors): Positional arguments to ``func`` that must all be
|
| 1108 |
+
Tensors. The returned function will also be computing the
|
| 1109 |
+
derivative with respect to these arguments
|
| 1110 |
+
tangents (Tensors): The "vector" for which Jacobian-vector-product is
|
| 1111 |
+
computed. Must be the same structure and sizes as the inputs to
|
| 1112 |
+
``func``.
|
| 1113 |
+
has_aux (bool): Flag indicating that ``func`` returns a
|
| 1114 |
+
``(output, aux)`` tuple where the first element is the output of
|
| 1115 |
+
the function to be differentiated and the second element is
|
| 1116 |
+
other auxiliary objects that will not be differentiated.
|
| 1117 |
+
Default: False.
|
| 1118 |
+
|
| 1119 |
+
Returns:
|
| 1120 |
+
Returns a ``(output, jvp_out)`` tuple containing the output of ``func``
|
| 1121 |
+
evaluated at ``primals`` and the Jacobian-vector product.
|
| 1122 |
+
If ``has_aux is True``, then instead returns a ``(output, jvp_out, aux)`` tuple.
|
| 1123 |
+
|
| 1124 |
+
.. note::
|
| 1125 |
+
You may see this API error out with "forward-mode AD not implemented
|
| 1126 |
+
for operator X". If so, please file a bug report and we will prioritize it.
|
| 1127 |
+
|
| 1128 |
+
jvp is useful when you wish to compute gradients of a function R^1 -> R^N
|
| 1129 |
+
|
| 1130 |
+
>>> from torch.func import jvp
|
| 1131 |
+
>>> x = torch.randn([])
|
| 1132 |
+
>>> f = lambda x: x * torch.tensor([1.0, 2.0, 3])
|
| 1133 |
+
>>> value, grad = jvp(f, (x,), (torch.tensor(1.0),))
|
| 1134 |
+
>>> assert torch.allclose(value, f(x))
|
| 1135 |
+
>>> assert torch.allclose(grad, torch.tensor([1.0, 2, 3]))
|
| 1136 |
+
|
| 1137 |
+
:func:`jvp` can support functions with multiple inputs by passing in the
|
| 1138 |
+
tangents for each of the inputs
|
| 1139 |
+
|
| 1140 |
+
>>> from torch.func import jvp
|
| 1141 |
+
>>> x = torch.randn(5)
|
| 1142 |
+
>>> y = torch.randn(5)
|
| 1143 |
+
>>> f = lambda x, y: (x * y)
|
| 1144 |
+
>>> _, output = jvp(f, (x, y), (torch.ones(5), torch.ones(5)))
|
| 1145 |
+
>>> assert torch.allclose(output, x + y)
|
| 1146 |
+
|
| 1147 |
+
"""
|
| 1148 |
+
|
| 1149 |
+
return _jvp_with_argnums(
|
| 1150 |
+
func, primals, tangents, argnums=None, strict=strict, has_aux=has_aux
|
| 1151 |
+
)
|
| 1152 |
+
|
| 1153 |
+
|
| 1154 |
+
def _jvp_with_argnums(
|
| 1155 |
+
func: Callable[..., Any],
|
| 1156 |
+
primals: Any,
|
| 1157 |
+
tangents: Any,
|
| 1158 |
+
argnums: argnums_t | None,
|
| 1159 |
+
*,
|
| 1160 |
+
strict: bool = False,
|
| 1161 |
+
has_aux: bool,
|
| 1162 |
+
) -> tuple[Any, Any] | tuple[Any, Any, Any]:
|
| 1163 |
+
# This is the same function as jvp but also accepts an argnums argument
|
| 1164 |
+
# Most args are the same as jvp except for the added argument
|
| 1165 |
+
# argnums (int or tuple[int, ...]): Optional, specifies the argument(s) to compute gradients with respect to.
|
| 1166 |
+
# If None, computes the gradients with respect to all inputs (used for jvp). Default: None
|
| 1167 |
+
# Because of this, tangents must be of length argnums and matches up to the corresponding primal whose index is
|
| 1168 |
+
# given by argnums
|
| 1169 |
+
#
|
| 1170 |
+
# WARN: Users should NOT call this function directly and should just be calling jvp.
|
| 1171 |
+
# It is only separated so that inputs passed to jacfwd but not differentiated get the correct wrappers.
|
| 1172 |
+
#
|
| 1173 |
+
# NOTE: All error messages are produced as if jvp was being called, even if this was called by jacfwd
|
| 1174 |
+
#
|
| 1175 |
+
# Returns the same two elements as :func:`jvp` but the returned tuple, ``jvp_out``, only has JVPs with respect to
|
| 1176 |
+
# the primals given by argnums
|
| 1177 |
+
if not isinstance(primals, tuple):
|
| 1178 |
+
raise RuntimeError(
|
| 1179 |
+
f"{jvp_str}: Expected primals to be a tuple. "
|
| 1180 |
+
f"E.g. it should be valid to call f(*primals)."
|
| 1181 |
+
)
|
| 1182 |
+
diff_args = primals if argnums is None else _slice_argnums(primals, argnums)
|
| 1183 |
+
flat_primals, primals_spec = tree_flatten(diff_args)
|
| 1184 |
+
flat_tangents, tangents_spec = tree_flatten(tangents)
|
| 1185 |
+
if primals_spec != tangents_spec:
|
| 1186 |
+
raise RuntimeError(
|
| 1187 |
+
f"{jvp_str}: Expected primals and tangents to have the same python "
|
| 1188 |
+
f"structure. For example, if primals is a tuple of 3 tensors, "
|
| 1189 |
+
f"tangents also must be. Got primals with structure {primals_spec} "
|
| 1190 |
+
f"and tangents with structure {tangents_spec}"
|
| 1191 |
+
)
|
| 1192 |
+
assert_non_empty_list_of_tensors(flat_primals, jvp_str, "primals")
|
| 1193 |
+
assert_non_empty_list_of_tensors(flat_tangents, jvp_str, "tangents")
|
| 1194 |
+
|
| 1195 |
+
global JVP_NESTING
|
| 1196 |
+
|
| 1197 |
+
with jvp_increment_nesting() as level:
|
| 1198 |
+
with fwAD._set_fwd_grad_enabled(True):
|
| 1199 |
+
ctx = fwAD.dual_level if JVP_NESTING == 1 else contextlib.nullcontext
|
| 1200 |
+
with ctx():
|
| 1201 |
+
flat_duals = tuple(
|
| 1202 |
+
fwAD.make_dual(p, t) for p, t in zip(flat_primals, flat_tangents)
|
| 1203 |
+
)
|
| 1204 |
+
duals = tree_unflatten(flat_duals, primals_spec)
|
| 1205 |
+
if argnums is not None:
|
| 1206 |
+
primals = _wrap_all_tensors(primals, level)
|
| 1207 |
+
duals = _replace_args(primals, duals, argnums)
|
| 1208 |
+
result_duals = func(*duals)
|
| 1209 |
+
aux: Any = None
|
| 1210 |
+
if has_aux:
|
| 1211 |
+
if not (isinstance(result_duals, tuple) and len(result_duals) == 2):
|
| 1212 |
+
raise RuntimeError(
|
| 1213 |
+
f"{jvp_str}: output of function f should be a tuple: (output, aux) "
|
| 1214 |
+
"if has_aux is True"
|
| 1215 |
+
)
|
| 1216 |
+
result_duals, aux = result_duals
|
| 1217 |
+
aux = _undo_create_differentiable(aux, level)
|
| 1218 |
+
|
| 1219 |
+
result_duals, spec = tree_flatten(result_duals)
|
| 1220 |
+
assert_non_empty_tensor_output(result_duals, jvp_str)
|
| 1221 |
+
|
| 1222 |
+
primals_out, tangents_out = zip(
|
| 1223 |
+
*[safe_unpack_dual(dual, strict) for dual in result_duals]
|
| 1224 |
+
)
|
| 1225 |
+
primals_out = tree_map(
|
| 1226 |
+
partial(_undo_create_differentiable, level=level), primals_out
|
| 1227 |
+
)
|
| 1228 |
+
tangents_out = tree_map(
|
| 1229 |
+
partial(_undo_create_differentiable, level=level), tangents_out
|
| 1230 |
+
)
|
| 1231 |
+
|
| 1232 |
+
primals_out_unflatten = tree_unflatten(primals_out, spec)
|
| 1233 |
+
tangents_out_unflatten = tree_unflatten(tangents_out, spec)
|
| 1234 |
+
if has_aux:
|
| 1235 |
+
return primals_out_unflatten, tangents_out_unflatten, aux # type: ignore[possibly-unbound]
|
| 1236 |
+
|
| 1237 |
+
return primals_out_unflatten, tangents_out_unflatten
|
| 1238 |
+
|
| 1239 |
+
|
| 1240 |
+
def safe_unflatten(tensor: torch.Tensor, dim: int, shape: torch.Size) -> torch.Tensor:
|
| 1241 |
+
if len(shape) == 0:
|
| 1242 |
+
if tensor.shape[dim] != 1:
|
| 1243 |
+
raise AssertionError(
|
| 1244 |
+
f"expected tensor.shape[{dim}] to be 1, got {tensor.shape[dim]}"
|
| 1245 |
+
)
|
| 1246 |
+
return tensor.squeeze(dim)
|
| 1247 |
+
return tensor.unflatten(dim, shape)
|
| 1248 |
+
|
| 1249 |
+
|
| 1250 |
+
@exposed_in("torch.func")
|
| 1251 |
+
def jacfwd(
|
| 1252 |
+
func: Callable[..., Any],
|
| 1253 |
+
argnums: argnums_t = 0,
|
| 1254 |
+
has_aux: bool = False,
|
| 1255 |
+
*,
|
| 1256 |
+
randomness: str = "error",
|
| 1257 |
+
) -> Callable[..., Any]:
|
| 1258 |
+
"""
|
| 1259 |
+
Computes the Jacobian of ``func`` with respect to the arg(s) at index
|
| 1260 |
+
``argnum`` using forward-mode autodiff
|
| 1261 |
+
|
| 1262 |
+
Args:
|
| 1263 |
+
func (function): A Python function that takes one or more arguments,
|
| 1264 |
+
one of which must be a Tensor, and returns one or more Tensors
|
| 1265 |
+
argnums (int or tuple[int, ...]): Optional, integer or tuple of integers,
|
| 1266 |
+
saying which arguments to get the Jacobian with respect to.
|
| 1267 |
+
Default: 0.
|
| 1268 |
+
has_aux (bool): Flag indicating that ``func`` returns a
|
| 1269 |
+
``(output, aux)`` tuple where the first element is the output of
|
| 1270 |
+
the function to be differentiated and the second element is
|
| 1271 |
+
auxiliary objects that will not be differentiated.
|
| 1272 |
+
Default: False.
|
| 1273 |
+
randomness(str): Flag indicating what type of randomness to use.
|
| 1274 |
+
See :func:`vmap` for more detail. Allowed: "different", "same", "error".
|
| 1275 |
+
Default: "error"
|
| 1276 |
+
|
| 1277 |
+
Returns:
|
| 1278 |
+
Returns a function that takes in the same inputs as ``func`` and
|
| 1279 |
+
returns the Jacobian of ``func`` with respect to the arg(s) at
|
| 1280 |
+
``argnums``. If ``has_aux is True``, then the returned function
|
| 1281 |
+
instead returns a ``(jacobian, aux)`` tuple where ``jacobian``
|
| 1282 |
+
is the Jacobian and ``aux`` is auxiliary objects returned by ``func``.
|
| 1283 |
+
|
| 1284 |
+
.. note::
|
| 1285 |
+
You may see this API error out with "forward-mode AD not implemented
|
| 1286 |
+
for operator X". If so, please file a bug report and we will prioritize it.
|
| 1287 |
+
An alternative is to use :func:`jacrev`, which has better operator coverage.
|
| 1288 |
+
|
| 1289 |
+
A basic usage with a pointwise, unary operation will give a diagonal array
|
| 1290 |
+
as the Jacobian
|
| 1291 |
+
|
| 1292 |
+
>>> from torch.func import jacfwd
|
| 1293 |
+
>>> x = torch.randn(5)
|
| 1294 |
+
>>> jacobian = jacfwd(torch.sin)(x)
|
| 1295 |
+
>>> expected = torch.diag(torch.cos(x))
|
| 1296 |
+
>>> assert torch.allclose(jacobian, expected)
|
| 1297 |
+
|
| 1298 |
+
:func:`jacfwd` can be composed with vmap to produce batched
|
| 1299 |
+
Jacobians:
|
| 1300 |
+
|
| 1301 |
+
>>> from torch.func import jacfwd, vmap
|
| 1302 |
+
>>> x = torch.randn(64, 5)
|
| 1303 |
+
>>> jacobian = vmap(jacfwd(torch.sin))(x)
|
| 1304 |
+
>>> assert jacobian.shape == (64, 5, 5)
|
| 1305 |
+
|
| 1306 |
+
If you would like to compute the output of the function as well as the
|
| 1307 |
+
jacobian of the function, use the ``has_aux`` flag to return the output
|
| 1308 |
+
as an auxiliary object:
|
| 1309 |
+
|
| 1310 |
+
>>> from torch.func import jacfwd
|
| 1311 |
+
>>> x = torch.randn(5)
|
| 1312 |
+
>>>
|
| 1313 |
+
>>> def f(x):
|
| 1314 |
+
>>> return x.sin()
|
| 1315 |
+
>>>
|
| 1316 |
+
>>> def g(x):
|
| 1317 |
+
>>> result = f(x)
|
| 1318 |
+
>>> return result, result
|
| 1319 |
+
>>>
|
| 1320 |
+
>>> jacobian_f, f_x = jacfwd(g, has_aux=True)(x)
|
| 1321 |
+
>>> assert torch.allclose(f_x, f(x))
|
| 1322 |
+
|
| 1323 |
+
Additionally, :func:`jacrev` can be composed with itself or :func:`jacrev`
|
| 1324 |
+
to produce Hessians
|
| 1325 |
+
|
| 1326 |
+
>>> from torch.func import jacfwd, jacrev
|
| 1327 |
+
>>> def f(x):
|
| 1328 |
+
>>> return x.sin().sum()
|
| 1329 |
+
>>>
|
| 1330 |
+
>>> x = torch.randn(5)
|
| 1331 |
+
>>> hessian = jacfwd(jacrev(f))(x)
|
| 1332 |
+
>>> assert torch.allclose(hessian, torch.diag(-x.sin()))
|
| 1333 |
+
|
| 1334 |
+
By default, :func:`jacfwd` computes the Jacobian with respect to the first
|
| 1335 |
+
input. However, it can compute the Jacboian with respect to a different
|
| 1336 |
+
argument by using ``argnums``:
|
| 1337 |
+
|
| 1338 |
+
>>> from torch.func import jacfwd
|
| 1339 |
+
>>> def f(x, y):
|
| 1340 |
+
>>> return x + y ** 2
|
| 1341 |
+
>>>
|
| 1342 |
+
>>> x, y = torch.randn(5), torch.randn(5)
|
| 1343 |
+
>>> jacobian = jacfwd(f, argnums=1)(x, y)
|
| 1344 |
+
>>> expected = torch.diag(2 * y)
|
| 1345 |
+
>>> assert torch.allclose(jacobian, expected)
|
| 1346 |
+
|
| 1347 |
+
Additionally, passing a tuple to ``argnums`` will compute the Jacobian
|
| 1348 |
+
with respect to multiple arguments
|
| 1349 |
+
|
| 1350 |
+
>>> from torch.func import jacfwd
|
| 1351 |
+
>>> def f(x, y):
|
| 1352 |
+
>>> return x + y ** 2
|
| 1353 |
+
>>>
|
| 1354 |
+
>>> x, y = torch.randn(5), torch.randn(5)
|
| 1355 |
+
>>> jacobian = jacfwd(f, argnums=(0, 1))(x, y)
|
| 1356 |
+
>>> expectedX = torch.diag(torch.ones_like(x))
|
| 1357 |
+
>>> expectedY = torch.diag(2 * y)
|
| 1358 |
+
>>> assert torch.allclose(jacobian[0], expectedX)
|
| 1359 |
+
>>> assert torch.allclose(jacobian[1], expectedY)
|
| 1360 |
+
|
| 1361 |
+
"""
|
| 1362 |
+
|
| 1363 |
+
@wraps(func)
|
| 1364 |
+
def wrapper_fn(*args: Any) -> Any:
|
| 1365 |
+
error_if_complex("jacfwd", args, is_input=True)
|
| 1366 |
+
primals = args if argnums is None else _slice_argnums(args, argnums)
|
| 1367 |
+
flat_primals, primals_spec = tree_flatten(primals)
|
| 1368 |
+
flat_primals_numels = tuple(p.numel() for p in flat_primals)
|
| 1369 |
+
flat_basis = _construct_standard_basis_for(flat_primals, flat_primals_numels)
|
| 1370 |
+
if flat_basis is None:
|
| 1371 |
+
raise AssertionError("flat_basis must not be None")
|
| 1372 |
+
basis = tree_unflatten(flat_basis, primals_spec)
|
| 1373 |
+
|
| 1374 |
+
def push_jvp(basis: Any) -> Any:
|
| 1375 |
+
output = _jvp_with_argnums(
|
| 1376 |
+
func, args, basis, argnums=argnums, has_aux=has_aux
|
| 1377 |
+
)
|
| 1378 |
+
# output[0] is the output of `func(*args)`
|
| 1379 |
+
error_if_complex("jacfwd", output[0], is_input=False)
|
| 1380 |
+
if has_aux:
|
| 1381 |
+
_, jvp_out, aux = output # pyrefly: ignore[bad-unpacking]
|
| 1382 |
+
return jvp_out, aux
|
| 1383 |
+
_, jvp_out = output # pyrefly: ignore[bad-unpacking]
|
| 1384 |
+
return jvp_out
|
| 1385 |
+
|
| 1386 |
+
results = vmap(push_jvp, randomness=randomness)(basis)
|
| 1387 |
+
aux: Any = None
|
| 1388 |
+
if has_aux:
|
| 1389 |
+
results, aux = results
|
| 1390 |
+
# aux is in the standard basis format, e.g. NxN matrix
|
| 1391 |
+
# We need to fetch the first element as original `func` output
|
| 1392 |
+
flat_aux, aux_spec = tree_flatten(aux)
|
| 1393 |
+
flat_aux = [value[0] for value in flat_aux]
|
| 1394 |
+
aux = tree_unflatten(flat_aux, aux_spec)
|
| 1395 |
+
|
| 1396 |
+
jac_outs, spec = tree_flatten(results)
|
| 1397 |
+
# Most probably below output check can never raise an error
|
| 1398 |
+
# as jvp should test the output before
|
| 1399 |
+
# assert_non_empty_output(jac_outs, 'jacfwd(f, ...)(*args)')
|
| 1400 |
+
|
| 1401 |
+
jac_outs_ins = tuple(
|
| 1402 |
+
tuple(
|
| 1403 |
+
safe_unflatten(jac_out_in, -1, primal.shape)
|
| 1404 |
+
for primal, jac_out_in in zip(
|
| 1405 |
+
flat_primals,
|
| 1406 |
+
jac_out.movedim(0, -1).split(flat_primals_numels, dim=-1),
|
| 1407 |
+
)
|
| 1408 |
+
)
|
| 1409 |
+
for jac_out in jac_outs
|
| 1410 |
+
)
|
| 1411 |
+
jac_outs_ins = tuple(
|
| 1412 |
+
tree_unflatten(jac_ins, primals_spec) for jac_ins in jac_outs_ins
|
| 1413 |
+
)
|
| 1414 |
+
|
| 1415 |
+
if isinstance(argnums, int):
|
| 1416 |
+
jac_outs_ins = tuple(jac_ins[0] for jac_ins in jac_outs_ins)
|
| 1417 |
+
if has_aux:
|
| 1418 |
+
return tree_unflatten(jac_outs_ins, spec), aux # type: ignore[possibly-unbound]
|
| 1419 |
+
return tree_unflatten(jac_outs_ins, spec)
|
| 1420 |
+
|
| 1421 |
+
return wrapper_fn
|
| 1422 |
+
|
| 1423 |
+
|
| 1424 |
+
@exposed_in("torch.func")
|
| 1425 |
+
def hessian(func: Callable[..., Any], argnums: argnums_t = 0) -> Callable[..., Any]:
|
| 1426 |
+
"""
|
| 1427 |
+
Computes the Hessian of ``func`` with respect to the arg(s) at index
|
| 1428 |
+
``argnum`` via a forward-over-reverse strategy.
|
| 1429 |
+
|
| 1430 |
+
The forward-over-reverse strategy (composing ``jacfwd(jacrev(func))``) is
|
| 1431 |
+
a good default for good performance. It is possible to compute Hessians
|
| 1432 |
+
through other compositions of :func:`jacfwd` and :func:`jacrev` like
|
| 1433 |
+
``jacfwd(jacfwd(func))`` or ``jacrev(jacrev(func))``.
|
| 1434 |
+
|
| 1435 |
+
Args:
|
| 1436 |
+
func (function): A Python function that takes one or more arguments,
|
| 1437 |
+
one of which must be a Tensor, and returns one or more Tensors
|
| 1438 |
+
argnums (int or tuple[int, ...]): Optional, integer or tuple of integers,
|
| 1439 |
+
saying which arguments to get the Hessian with respect to.
|
| 1440 |
+
Default: 0.
|
| 1441 |
+
|
| 1442 |
+
Returns:
|
| 1443 |
+
Returns a function that takes in the same inputs as ``func`` and
|
| 1444 |
+
returns the Hessian of ``func`` with respect to the arg(s) at
|
| 1445 |
+
``argnums``.
|
| 1446 |
+
|
| 1447 |
+
.. note::
|
| 1448 |
+
You may see this API error out with "forward-mode AD not implemented
|
| 1449 |
+
for operator X". If so, please file a bug report and we will prioritize it.
|
| 1450 |
+
An alternative is to use ``jacrev(jacrev(func))``, which has better
|
| 1451 |
+
operator coverage.
|
| 1452 |
+
|
| 1453 |
+
A basic usage with a R^N -> R^1 function gives a N x N Hessian:
|
| 1454 |
+
|
| 1455 |
+
>>> from torch.func import hessian
|
| 1456 |
+
>>> def f(x):
|
| 1457 |
+
>>> return x.sin().sum()
|
| 1458 |
+
>>>
|
| 1459 |
+
>>> x = torch.randn(5)
|
| 1460 |
+
>>> hess = hessian(f)(x) # equivalent to jacfwd(jacrev(f))(x)
|
| 1461 |
+
>>> assert torch.allclose(hess, torch.diag(-x.sin()))
|
| 1462 |
+
|
| 1463 |
+
"""
|
| 1464 |
+
return jacfwd(jacrev(func, argnums), argnums)
|
| 1465 |
+
|
| 1466 |
+
|
| 1467 |
+
@doesnt_support_saved_tensors_hooks
|
| 1468 |
+
def grad_and_value_impl(
|
| 1469 |
+
func: Callable[..., Any],
|
| 1470 |
+
argnums: argnums_t,
|
| 1471 |
+
has_aux: bool,
|
| 1472 |
+
args: tuple[Any, ...],
|
| 1473 |
+
kwargs: dict[str, Any],
|
| 1474 |
+
) -> tuple[Any, Any]:
|
| 1475 |
+
with grad_increment_nesting() as level:
|
| 1476 |
+
output, aux, grad_input = None, None, None
|
| 1477 |
+
# See NOTE [grad and vjp interaction with no_grad]
|
| 1478 |
+
with torch.enable_grad():
|
| 1479 |
+
args = _wrap_all_tensors(args, level)
|
| 1480 |
+
kwargs = _wrap_all_tensors(kwargs, level)
|
| 1481 |
+
diff_args = _slice_argnums(args, argnums, as_tuple=False)
|
| 1482 |
+
tree_map_(partial(_create_differentiable, level=level), diff_args)
|
| 1483 |
+
|
| 1484 |
+
output = func(*args, **kwargs)
|
| 1485 |
+
if has_aux:
|
| 1486 |
+
if not (isinstance(output, tuple) and len(output) == 2):
|
| 1487 |
+
raise RuntimeError(
|
| 1488 |
+
"grad_and_value(f)(*args): output of function f should be a tuple: (output, aux) "
|
| 1489 |
+
"if has_aux is True"
|
| 1490 |
+
)
|
| 1491 |
+
output, aux = output
|
| 1492 |
+
|
| 1493 |
+
if not isinstance(output, torch.Tensor):
|
| 1494 |
+
raise RuntimeError(
|
| 1495 |
+
"grad_and_value(f)(*args): Expected f(*args) "
|
| 1496 |
+
f"to return a Tensor, got {type(output)}"
|
| 1497 |
+
)
|
| 1498 |
+
if output.dim() != 0:
|
| 1499 |
+
raise RuntimeError(
|
| 1500 |
+
"grad_and_value(f)(*args): Expected f(*args) "
|
| 1501 |
+
"to return a scalar Tensor, got tensor with "
|
| 1502 |
+
f"{output.dim()} dims. Maybe you wanted to "
|
| 1503 |
+
"use the vjp or jacrev APIs instead?"
|
| 1504 |
+
)
|
| 1505 |
+
|
| 1506 |
+
flat_diff_args, spec = tree_flatten(diff_args)
|
| 1507 |
+
|
| 1508 |
+
# NB: need create_graph so that backward pass isn't run in no_grad mode
|
| 1509 |
+
flat_outputs = _as_tuple(output)
|
| 1510 |
+
flat_grad_input = _autograd_grad(
|
| 1511 |
+
flat_outputs, flat_diff_args, create_graph=True
|
| 1512 |
+
)
|
| 1513 |
+
grad_input = tree_unflatten(flat_grad_input, spec)
|
| 1514 |
+
|
| 1515 |
+
grad_input = _undo_create_differentiable(grad_input, level)
|
| 1516 |
+
output = _undo_create_differentiable(output, level)
|
| 1517 |
+
if has_aux:
|
| 1518 |
+
# pyrefly: ignore[bad-specialization]
|
| 1519 |
+
aux = _undo_create_differentiable(aux, level)
|
| 1520 |
+
|
| 1521 |
+
if has_aux:
|
| 1522 |
+
return grad_input, (output, aux)
|
| 1523 |
+
return grad_input, output
|
| 1524 |
+
|
| 1525 |
+
|
| 1526 |
+
def grad_impl(
|
| 1527 |
+
func: Callable[..., Any],
|
| 1528 |
+
argnums: argnums_t,
|
| 1529 |
+
has_aux: bool,
|
| 1530 |
+
args: tuple[Any, ...],
|
| 1531 |
+
kwargs: dict[str, Any],
|
| 1532 |
+
) -> Any:
|
| 1533 |
+
results = grad_and_value_impl(func, argnums, has_aux, args, kwargs)
|
| 1534 |
+
if has_aux:
|
| 1535 |
+
grad, (_, aux) = results
|
| 1536 |
+
return grad, aux
|
| 1537 |
+
grad, _ = results
|
| 1538 |
+
return grad
|
| 1539 |
+
|
| 1540 |
+
|
| 1541 |
+
def _maybe_wrap_functional_tensor(
|
| 1542 |
+
maybe_tensor: Any, level: int, *, _python_functionalize: bool = False
|
| 1543 |
+
) -> Any:
|
| 1544 |
+
if not isinstance(maybe_tensor, torch.Tensor):
|
| 1545 |
+
return maybe_tensor
|
| 1546 |
+
wrapped = _wrap_functional_tensor(maybe_tensor, level)
|
| 1547 |
+
_assert_wrapped_functional(maybe_tensor, wrapped)
|
| 1548 |
+
if _python_functionalize:
|
| 1549 |
+
# pyrefly: ignore[missing-argument]
|
| 1550 |
+
out = FunctionalTensor(wrapped)
|
| 1551 |
+
# pyrefly: ignore[missing-attribute]
|
| 1552 |
+
torch._mirror_autograd_meta_to(maybe_tensor, out)
|
| 1553 |
+
return out
|
| 1554 |
+
return wrapped
|
| 1555 |
+
|
| 1556 |
+
|
| 1557 |
+
def _wrap_all_tensors_to_functional(
|
| 1558 |
+
tensor_pytree: Any, level: int, *, _python_functionalize: bool = False
|
| 1559 |
+
) -> Any:
|
| 1560 |
+
return tree_map(
|
| 1561 |
+
partial(
|
| 1562 |
+
lambda x: _maybe_wrap_functional_tensor(
|
| 1563 |
+
x, level, _python_functionalize=_python_functionalize
|
| 1564 |
+
)
|
| 1565 |
+
),
|
| 1566 |
+
tensor_pytree,
|
| 1567 |
+
)
|
| 1568 |
+
|
| 1569 |
+
|
| 1570 |
+
def _maybe_unwrap_functional_tensor(maybe_tensor: Any, *, reapply_views: bool) -> Any:
|
| 1571 |
+
if not isinstance(maybe_tensor, torch.Tensor):
|
| 1572 |
+
return maybe_tensor
|
| 1573 |
+
if isinstance(maybe_tensor, FunctionalTensor):
|
| 1574 |
+
maybe_tensor = maybe_tensor.elem
|
| 1575 |
+
|
| 1576 |
+
if not torch._is_functional_tensor(maybe_tensor):
|
| 1577 |
+
# If it's not a functional tensor, just return it.
|
| 1578 |
+
# This can happen if we functionalize a fn that returns a global,
|
| 1579 |
+
# which was never wrapped properly.
|
| 1580 |
+
return maybe_tensor
|
| 1581 |
+
# Sync any pending updates on the output tensor
|
| 1582 |
+
torch._sync(maybe_tensor)
|
| 1583 |
+
return _unwrap_functional_tensor(maybe_tensor, reapply_views)
|
| 1584 |
+
|
| 1585 |
+
|
| 1586 |
+
def _unwrap_all_tensors_from_functional(
|
| 1587 |
+
tensor_pytree: Any, *, reapply_views: bool
|
| 1588 |
+
) -> Any:
|
| 1589 |
+
return tree_map(
|
| 1590 |
+
lambda t: _maybe_unwrap_functional_tensor(t, reapply_views=reapply_views),
|
| 1591 |
+
tensor_pytree,
|
| 1592 |
+
)
|
| 1593 |
+
|
| 1594 |
+
|
| 1595 |
+
@exposed_in("torch.func")
|
| 1596 |
+
def functionalize(
|
| 1597 |
+
func: Callable[..., Any], *, remove: str = "mutations"
|
| 1598 |
+
) -> Callable[..., Any]:
|
| 1599 |
+
"""
|
| 1600 |
+
functionalize is a transform that can be used to remove (intermediate)
|
| 1601 |
+
mutations and aliasing from a function, while preserving the function's
|
| 1602 |
+
semantics.
|
| 1603 |
+
|
| 1604 |
+
``functionalize(func)`` returns a new function with the same semantics
|
| 1605 |
+
as ``func``, but with all intermediate mutations removed.
|
| 1606 |
+
Every inplace operation performed on an intermediate tensor:
|
| 1607 |
+
``intermediate.foo_()``
|
| 1608 |
+
gets replaced by its out-of-place equivalent:
|
| 1609 |
+
``intermediate_updated = intermediate.foo()``.
|
| 1610 |
+
|
| 1611 |
+
functionalize is useful for shipping a pytorch program off to
|
| 1612 |
+
backends or compilers that aren't able to easily represent
|
| 1613 |
+
mutations or aliasing operators.
|
| 1614 |
+
|
| 1615 |
+
Args:
|
| 1616 |
+
func (Callable[..., Any]): A Python function that takes one or more arguments.
|
| 1617 |
+
remove (str): An optional string argument, that takes on either
|
| 1618 |
+
the value 'mutations' or 'mutations_and_views'.
|
| 1619 |
+
If 'mutations' is passed in then all mutating operators
|
| 1620 |
+
will be replaced with their non-mutating equivalents.
|
| 1621 |
+
If 'mutations_and_views' is passed in, then additionally, all aliasing
|
| 1622 |
+
operators will be replaced with their non-aliasing equivalents.
|
| 1623 |
+
Default: 'mutations'.
|
| 1624 |
+
|
| 1625 |
+
Returns:
|
| 1626 |
+
Returns a new "functionalized" function. It takes the same inputs as
|
| 1627 |
+
``func``, and has the same behavior, but any mutations
|
| 1628 |
+
(and optionally aliasing) performed on intermediate tensors
|
| 1629 |
+
in the function will be removed.
|
| 1630 |
+
|
| 1631 |
+
functionalize will also remove mutations (and views) that were performed on function inputs.
|
| 1632 |
+
However to preserve semantics, functionalize will "fix up" the mutations after
|
| 1633 |
+
the transform has finished running, by detecting if any tensor inputs "should have"
|
| 1634 |
+
been mutated, and copying the new data back to the inputs if necessary.
|
| 1635 |
+
|
| 1636 |
+
|
| 1637 |
+
Example::
|
| 1638 |
+
|
| 1639 |
+
>>> # xdoctest: +SKIP
|
| 1640 |
+
>>> import torch
|
| 1641 |
+
>>> from torch.fx.experimental.proxy_tensor import make_fx
|
| 1642 |
+
>>> from torch.func import functionalize
|
| 1643 |
+
>>>
|
| 1644 |
+
>>> # A function that uses mutations and views, but only on intermediate tensors.
|
| 1645 |
+
>>> def f(a):
|
| 1646 |
+
... b = a + 1
|
| 1647 |
+
... c = b.view(-1)
|
| 1648 |
+
... c.add_(1)
|
| 1649 |
+
... return b
|
| 1650 |
+
...
|
| 1651 |
+
>>> inpt = torch.randn(2)
|
| 1652 |
+
>>>
|
| 1653 |
+
>>> out1 = f(inpt)
|
| 1654 |
+
>>> out2 = functionalize(f)(inpt)
|
| 1655 |
+
>>>
|
| 1656 |
+
>>> # semantics are the same (outputs are equivalent)
|
| 1657 |
+
>>> print(torch.allclose(out1, out2))
|
| 1658 |
+
True
|
| 1659 |
+
>>>
|
| 1660 |
+
>>> f_traced = make_fx(f)(inpt)
|
| 1661 |
+
>>> f_no_mutations_traced = make_fx(functionalize(f))(inpt)
|
| 1662 |
+
>>> f_no_mutations_and_views_traced = make_fx(functionalize(f, remove='mutations_and_views'))(inpt)
|
| 1663 |
+
>>>
|
| 1664 |
+
>>> print(f_traced.code)
|
| 1665 |
+
|
| 1666 |
+
|
| 1667 |
+
|
| 1668 |
+
def forward(self, a_1):
|
| 1669 |
+
add = torch.ops.aten.add(a_1, 1); a_1 = None
|
| 1670 |
+
view = torch.ops.aten.view(add, [-1])
|
| 1671 |
+
add_ = torch.ops.aten.add_(view, 1); view = None
|
| 1672 |
+
return add
|
| 1673 |
+
|
| 1674 |
+
>>> print(f_no_mutations_traced.code)
|
| 1675 |
+
|
| 1676 |
+
|
| 1677 |
+
|
| 1678 |
+
def forward(self, a_1):
|
| 1679 |
+
add = torch.ops.aten.add(a_1, 1); a_1 = None
|
| 1680 |
+
view = torch.ops.aten.view(add, [-1]); add = None
|
| 1681 |
+
add_1 = torch.ops.aten.add(view, 1); view = None
|
| 1682 |
+
view_1 = torch.ops.aten.view(add_1, [2]); add_1 = None
|
| 1683 |
+
return view_1
|
| 1684 |
+
|
| 1685 |
+
>>> print(f_no_mutations_and_views_traced.code)
|
| 1686 |
+
|
| 1687 |
+
|
| 1688 |
+
|
| 1689 |
+
def forward(self, a_1):
|
| 1690 |
+
add = torch.ops.aten.add(a_1, 1); a_1 = None
|
| 1691 |
+
view_copy = torch.ops.aten.view_copy(add, [-1]); add = None
|
| 1692 |
+
add_1 = torch.ops.aten.add(view_copy, 1); view_copy = None
|
| 1693 |
+
view_copy_1 = torch.ops.aten.view_copy(add_1, [2]); add_1 = None
|
| 1694 |
+
return view_copy_1
|
| 1695 |
+
|
| 1696 |
+
|
| 1697 |
+
>>> # A function that mutates its input tensor
|
| 1698 |
+
>>> def f(a):
|
| 1699 |
+
... b = a.view(-1)
|
| 1700 |
+
... b.add_(1)
|
| 1701 |
+
... return a
|
| 1702 |
+
...
|
| 1703 |
+
>>> f_no_mutations_and_views_traced = make_fx(functionalize(f, remove='mutations_and_views'))(inpt)
|
| 1704 |
+
>>> #
|
| 1705 |
+
>>> # All mutations and views have been removed,
|
| 1706 |
+
>>> # but there is an extra copy_ in the graph to correctly apply the mutation to the input
|
| 1707 |
+
>>> # after the function has completed.
|
| 1708 |
+
>>> print(f_no_mutations_and_views_traced.code)
|
| 1709 |
+
|
| 1710 |
+
|
| 1711 |
+
|
| 1712 |
+
def forward(self, a_1):
|
| 1713 |
+
view_copy = torch.ops.aten.view_copy(a_1, [-1])
|
| 1714 |
+
add = torch.ops.aten.add(view_copy, 1); view_copy = None
|
| 1715 |
+
view_copy_1 = torch.ops.aten.view_copy(add, [2]); add = None
|
| 1716 |
+
copy_ = torch.ops.aten.copy_(a_1, view_copy_1); a_1 = None
|
| 1717 |
+
return view_copy_1
|
| 1718 |
+
|
| 1719 |
+
|
| 1720 |
+
There are a few "failure modes" for functionalize that are worth calling out:
|
| 1721 |
+
(1) Like other torch.func transforms, `functionalize()` doesn't work with functions
|
| 1722 |
+
that directly use `.backward()`. The same is true for torch.autograd.grad.
|
| 1723 |
+
If you want to use autograd, you can compute gradients directly
|
| 1724 |
+
with `functionalize(grad(f))`.
|
| 1725 |
+
(2) Like other torch.func transforms, `functionalize()` doesn't work with global state.
|
| 1726 |
+
If you call `functionalize(f)` on a function that takes views / mutations of
|
| 1727 |
+
non-local state, functionalization will simply no-op and pass the view/mutation
|
| 1728 |
+
calls directly to the backend.
|
| 1729 |
+
One way to work around this is to ensure that any non-local state creation
|
| 1730 |
+
is wrapped into a larger function, which you then call functionalize on.
|
| 1731 |
+
(3) `resize_()` has some limitations: functionalize will only work on programs
|
| 1732 |
+
that use resize_()` as long as the tensor being resized is not a view.
|
| 1733 |
+
(4) `as_strided()` has some limitations: functionalize will not work on
|
| 1734 |
+
`as_strided()` calls that result in tensors with overlapping memory.
|
| 1735 |
+
|
| 1736 |
+
|
| 1737 |
+
Finally, a helpful mental model for understanding functionalization is that
|
| 1738 |
+
most user pytorch programs are writing with the public torch API.
|
| 1739 |
+
When executed, torch operators are generally decomposed into
|
| 1740 |
+
our internal C++ "ATen" API.
|
| 1741 |
+
The logic for functionalization happens entirely at the level of ATen.
|
| 1742 |
+
Functionalization knows how to take every aliasing operator in ATen,
|
| 1743 |
+
and map it to its non-aliasing equivalent
|
| 1744 |
+
(e.g. ``tensor.view({-1})`` -> ``at::view_copy(tensor, {-1})``),
|
| 1745 |
+
and how to take every mutating operator in ATen,
|
| 1746 |
+
and map it to its non-mutating equivalent
|
| 1747 |
+
(e.g. ``tensor.add_(1)`` -> ``at::add(tensor, -1)``),
|
| 1748 |
+
while tracking aliases and mutations out-of-line to know when to fix things up.
|
| 1749 |
+
Information about which ATen operators are aliasing or mutating all comes from
|
| 1750 |
+
https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/native_functions.yaml.
|
| 1751 |
+
"""
|
| 1752 |
+
if remove == "mutations":
|
| 1753 |
+
reapply_views = True
|
| 1754 |
+
elif remove == "mutations_and_views":
|
| 1755 |
+
reapply_views = False
|
| 1756 |
+
else:
|
| 1757 |
+
raise RuntimeError(
|
| 1758 |
+
f"functionalize(f, remove='mutations'): received invalid argument for remove={remove}."
|
| 1759 |
+
" Valid options are:\n"
|
| 1760 |
+
" remove='mutations': all inplace and out= operators will be removed from the program, and replaced"
|
| 1761 |
+
" with their out-of-place equivalents.\n"
|
| 1762 |
+
" remove='mutations_and_views': In addition to the above, all aliasing operators {view} will be"
|
| 1763 |
+
" replaced with their non-aliasing counterparts, {view}_copy.\n"
|
| 1764 |
+
)
|
| 1765 |
+
|
| 1766 |
+
@wraps(func)
|
| 1767 |
+
def wrapped(*args: Any, **kwargs: Any) -> Any:
|
| 1768 |
+
try:
|
| 1769 |
+
func_level = _func_increment_nesting(reapply_views)
|
| 1770 |
+
func_args = _wrap_all_tensors_to_functional(args, func_level)
|
| 1771 |
+
func_kwargs = _wrap_all_tensors_to_functional(kwargs, func_level)
|
| 1772 |
+
|
| 1773 |
+
flattened_unwrapped_args = pytree.arg_tree_leaves(*args)
|
| 1774 |
+
flattened_wrapped_args = pytree.arg_tree_leaves(*func_args)
|
| 1775 |
+
flattened_unwrapped_kwargs = pytree.arg_tree_leaves(**kwargs)
|
| 1776 |
+
flattened_wrapped_kwargs = pytree.arg_tree_leaves(**func_kwargs)
|
| 1777 |
+
|
| 1778 |
+
func_outputs = func(*func_args, **func_kwargs)
|
| 1779 |
+
outputs = _unwrap_all_tensors_from_functional(
|
| 1780 |
+
func_outputs, reapply_views=reapply_views
|
| 1781 |
+
)
|
| 1782 |
+
|
| 1783 |
+
for a in flattened_wrapped_args + flattened_wrapped_kwargs:
|
| 1784 |
+
if isinstance(a, torch.Tensor):
|
| 1785 |
+
# Call sync_() on the inputs, to ensure that any pending mutations have been applied.
|
| 1786 |
+
torch._sync(a)
|
| 1787 |
+
|
| 1788 |
+
# And if any mutations were applied to the inputs, we need to propagate them back to the user.
|
| 1789 |
+
for unwrapped, wrapped in zip(
|
| 1790 |
+
flattened_unwrapped_args, flattened_wrapped_args
|
| 1791 |
+
):
|
| 1792 |
+
if isinstance(unwrapped, torch.Tensor) and isinstance(
|
| 1793 |
+
wrapped, torch.Tensor
|
| 1794 |
+
):
|
| 1795 |
+
_propagate_functional_input_mutation(unwrapped, wrapped)
|
| 1796 |
+
for unwrapped, wrapped in zip(
|
| 1797 |
+
flattened_unwrapped_kwargs, flattened_wrapped_kwargs
|
| 1798 |
+
):
|
| 1799 |
+
if isinstance(unwrapped, torch.Tensor) and isinstance(
|
| 1800 |
+
wrapped, torch.Tensor
|
| 1801 |
+
):
|
| 1802 |
+
_propagate_functional_input_mutation(unwrapped, wrapped)
|
| 1803 |
+
|
| 1804 |
+
return outputs
|
| 1805 |
+
finally:
|
| 1806 |
+
_func_decrement_nesting()
|
| 1807 |
+
|
| 1808 |
+
return wrapped
|
| 1809 |
+
|
| 1810 |
+
|
| 1811 |
+
@exposed_in("torch.func")
|
| 1812 |
+
def linearize(
|
| 1813 |
+
func: Callable[..., Any], *primals: Any
|
| 1814 |
+
) -> tuple[Any, Callable[..., Any]]:
|
| 1815 |
+
"""
|
| 1816 |
+
Returns the value of ``func`` at ``primals`` and linear approximation
|
| 1817 |
+
at ``primals``.
|
| 1818 |
+
|
| 1819 |
+
Args:
|
| 1820 |
+
func (Callable[..., Any]): A Python function that takes one or more arguments.
|
| 1821 |
+
primals (Tensors): Positional arguments to ``func`` that must all be
|
| 1822 |
+
Tensors. These are the values at which the function is linearly approximated.
|
| 1823 |
+
|
| 1824 |
+
Returns:
|
| 1825 |
+
Returns a ``(output, jvp_fn)`` tuple containing the output of ``func``
|
| 1826 |
+
applied to ``primals`` and a function that computes the jvp of
|
| 1827 |
+
``func`` evaluated at ``primals``.
|
| 1828 |
+
|
| 1829 |
+
linearize is useful if jvp is to be computed multiple times at ``primals``. However,
|
| 1830 |
+
to achieve this, linearize saves intermediate computation and has higher memory requirements
|
| 1831 |
+
than directly applying `jvp`. So, if all the ``tangents`` are known, it maybe more efficient
|
| 1832 |
+
to compute vmap(jvp) instead of using linearize.
|
| 1833 |
+
|
| 1834 |
+
.. note::
|
| 1835 |
+
linearize evaluates ``func`` twice. Please file an issue for an implementation
|
| 1836 |
+
with a single evaluation.
|
| 1837 |
+
|
| 1838 |
+
Example::
|
| 1839 |
+
|
| 1840 |
+
>>> import torch
|
| 1841 |
+
>>> from torch.func import linearize
|
| 1842 |
+
>>> def fn(x):
|
| 1843 |
+
... return x.sin()
|
| 1844 |
+
...
|
| 1845 |
+
>>> output, jvp_fn = linearize(fn, torch.zeros(3, 3))
|
| 1846 |
+
>>> jvp_fn(torch.ones(3, 3))
|
| 1847 |
+
tensor([[1., 1., 1.],
|
| 1848 |
+
[1., 1., 1.],
|
| 1849 |
+
[1., 1., 1.]])
|
| 1850 |
+
>>>
|
| 1851 |
+
|
| 1852 |
+
"""
|
| 1853 |
+
# Note: We evaluate `fn` twice.
|
| 1854 |
+
# Once for returning the output and other while
|
| 1855 |
+
# tracing the graph.
|
| 1856 |
+
# If this becomes a bottle-neck, we should update
|
| 1857 |
+
# make_fx such that it also returns the output.
|
| 1858 |
+
|
| 1859 |
+
output = func(*primals)
|
| 1860 |
+
_, output_spec = tree_flatten(output)
|
| 1861 |
+
|
| 1862 |
+
flat_primals, primals_argspec = tree_flatten(primals)
|
| 1863 |
+
|
| 1864 |
+
# tangents for tracing
|
| 1865 |
+
flat_tangents = tuple(p.new_empty(()).expand_as(p) for p in flat_primals)
|
| 1866 |
+
|
| 1867 |
+
# function to trace
|
| 1868 |
+
def trace_fn(flat_tangents: tuple[torch.Tensor, ...]) -> Any:
|
| 1869 |
+
with fwAD.dual_level():
|
| 1870 |
+
flat_duals = tuple(
|
| 1871 |
+
fwAD.make_dual(p, t) for p, t in zip(flat_primals, flat_tangents)
|
| 1872 |
+
)
|
| 1873 |
+
duals = tree_unflatten(flat_duals, primals_argspec)
|
| 1874 |
+
output = func(*duals)
|
| 1875 |
+
tangents = tree_map_only(
|
| 1876 |
+
torch.Tensor, lambda dual: safe_unpack_dual(dual, False)[1], output
|
| 1877 |
+
)
|
| 1878 |
+
|
| 1879 |
+
return tangents
|
| 1880 |
+
|
| 1881 |
+
jvp_graph = lazy_dynamo_disallow(make_fx)(trace_fn)(flat_tangents)
|
| 1882 |
+
const_folded_jvp_graph = lazy_dynamo_disallow(const_fold.split_const_subgraphs)(
|
| 1883 |
+
jvp_graph
|
| 1884 |
+
)
|
| 1885 |
+
|
| 1886 |
+
# Hold only the meta-data regarding the primals.
|
| 1887 |
+
flat_primals_shape = tuple(p.shape for p in flat_primals)
|
| 1888 |
+
flat_primals_device = tuple(p.device for p in flat_primals)
|
| 1889 |
+
flat_primals_dtype = tuple(p.dtype for p in flat_primals)
|
| 1890 |
+
|
| 1891 |
+
def forward_ad_checks(flat_tangents: Sequence[torch.Tensor]) -> None:
|
| 1892 |
+
for idx, t in enumerate(flat_tangents):
|
| 1893 |
+
if t.shape != flat_primals_shape[idx]:
|
| 1894 |
+
msg = (
|
| 1895 |
+
f"tangent:{idx} with shape {t.shape} in flattened "
|
| 1896 |
+
f"pytree doesn't match the shape {flat_primals_shape[idx]} "
|
| 1897 |
+
"of the corresponding primal."
|
| 1898 |
+
)
|
| 1899 |
+
raise RuntimeError(msg)
|
| 1900 |
+
|
| 1901 |
+
if t.device != flat_primals_device[idx]:
|
| 1902 |
+
msg = (
|
| 1903 |
+
f"tangent:{idx} with device {t.device} in flattened "
|
| 1904 |
+
f"pytree doesn't match the device {flat_primals_device[idx]} "
|
| 1905 |
+
"of the corresponding primal."
|
| 1906 |
+
)
|
| 1907 |
+
raise RuntimeError(msg)
|
| 1908 |
+
|
| 1909 |
+
if t.dtype != flat_primals_dtype[idx]:
|
| 1910 |
+
msg = (
|
| 1911 |
+
f"tangent:{idx} with dtype {t.dtype} in flattened "
|
| 1912 |
+
f"pytree doesn't match the dtype {flat_primals_dtype[idx]} "
|
| 1913 |
+
"of the corresponding primal."
|
| 1914 |
+
)
|
| 1915 |
+
raise RuntimeError(msg)
|
| 1916 |
+
|
| 1917 |
+
# jvp_fn : Callable[..., Any] to return
|
| 1918 |
+
# It takes care of checking the argspec of tangents,
|
| 1919 |
+
# calling the folded fx graph and unflattening fx graph output
|
| 1920 |
+
def jvp_fn(*tangents: Any) -> Any:
|
| 1921 |
+
flat_tangents, tangent_argspec = tree_flatten(tangents)
|
| 1922 |
+
if tangent_argspec != primals_argspec:
|
| 1923 |
+
raise RuntimeError(
|
| 1924 |
+
f"Expected the tangents {tangent_argspec} to have "
|
| 1925 |
+
f"the same argspec as the primals {primals_argspec}"
|
| 1926 |
+
)
|
| 1927 |
+
|
| 1928 |
+
forward_ad_checks(flat_tangents) # type: ignore[arg-type]
|
| 1929 |
+
|
| 1930 |
+
flat_output = const_folded_jvp_graph(*flat_tangents)
|
| 1931 |
+
# const folded graph can return flat output,
|
| 1932 |
+
# so transform output.
|
| 1933 |
+
return tree_unflatten(flat_output, output_spec)
|
| 1934 |
+
|
| 1935 |
+
return output, jvp_fn
|
| 1936 |
+
|
| 1937 |
+
|
| 1938 |
+
@exposed_in("torch.func")
|
| 1939 |
+
def debug_unwrap(tensor: torch.Tensor, *, recurse: bool = True) -> torch.Tensor:
|
| 1940 |
+
"""Unwraps a functorch tensor (e.g. BatchedTensor, GradTrackingTensor) to its underlying tensor.
|
| 1941 |
+
|
| 1942 |
+
This function should only be used in a debug setting (e.g. trying to print the
|
| 1943 |
+
value of a Tensor in a debugger). Otherwise, using the result of function
|
| 1944 |
+
inside of a function being transformed will lead to undefined behavior.
|
| 1945 |
+
"""
|
| 1946 |
+
if not is_functorch_wrapped_tensor(tensor):
|
| 1947 |
+
return tensor
|
| 1948 |
+
result = get_unwrapped(tensor)
|
| 1949 |
+
if recurse:
|
| 1950 |
+
return debug_unwrap(result)
|
| 1951 |
+
return result
|
venv/lib/python3.14/site-packages/torch/_functorch/functional_call.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Sequence
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
from torch._functorch.utils import exposed_in
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@exposed_in("torch.func")
|
| 13 |
+
def functional_call(
|
| 14 |
+
module: torch.nn.Module,
|
| 15 |
+
parameter_and_buffer_dicts: dict[str, Tensor] | Sequence[dict[str, Tensor]],
|
| 16 |
+
args: Any = None,
|
| 17 |
+
kwargs: dict[str, Any] | None = None,
|
| 18 |
+
*,
|
| 19 |
+
tie_weights: bool = True,
|
| 20 |
+
strict: bool = False,
|
| 21 |
+
) -> Any:
|
| 22 |
+
r"""Performs a functional call on the module by replacing the module parameters
|
| 23 |
+
and buffers with the provided ones.
|
| 24 |
+
|
| 25 |
+
.. note:: If the module has active parametrizations, passing a value in the
|
| 26 |
+
:attr:`parameter_and_buffer_dicts` argument with the name set to the regular parameter
|
| 27 |
+
name will completely disable the parametrization.
|
| 28 |
+
If you want to apply the parametrization function to the value passed
|
| 29 |
+
please set the key as ``{submodule_name}.parametrizations.{parameter_name}.original``.
|
| 30 |
+
|
| 31 |
+
.. note:: If the module performs in-place operations on parameters/buffers, these will be reflected
|
| 32 |
+
in the ``parameter_and_buffer_dicts`` input.
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
Example::
|
| 36 |
+
|
| 37 |
+
>>> a = {'foo': torch.zeros(())}
|
| 38 |
+
>>> # xdoctest: +SKIP
|
| 39 |
+
>>> mod = Foo() # does self.foo = self.foo + 1
|
| 40 |
+
>>> print(mod.foo) # tensor(0.)
|
| 41 |
+
>>> functional_call(mod, a, torch.ones(()))
|
| 42 |
+
>>> print(mod.foo) # tensor(0.)
|
| 43 |
+
>>> print(a['foo']) # tensor(1.)
|
| 44 |
+
|
| 45 |
+
.. note:: If the module has tied weights, whether or not functional_call respects the tying is determined by the
|
| 46 |
+
tie_weights flag.
|
| 47 |
+
|
| 48 |
+
Example::
|
| 49 |
+
|
| 50 |
+
>>> a = {'foo': torch.zeros(())}
|
| 51 |
+
>>> # xdoctest: +SKIP
|
| 52 |
+
>>> mod = Foo() # has both self.foo and self.foo_tied which are tied. Returns x + self.foo + self.foo_tied
|
| 53 |
+
>>> print(mod.foo) # tensor(1.)
|
| 54 |
+
>>> mod(torch.zeros(())) # tensor(2.)
|
| 55 |
+
>>> functional_call(mod, a, torch.zeros(())) # tensor(0.) since it will change self.foo_tied too
|
| 56 |
+
>>> functional_call(mod, a, torch.zeros(()), tie_weights=False) # tensor(1.)--self.foo_tied is not updated
|
| 57 |
+
>>> new_a = {'foo': torch.zeros(()), 'foo_tied': torch.zeros(())}
|
| 58 |
+
>>> functional_call(mod, new_a, torch.zeros()) # tensor(0.)
|
| 59 |
+
|
| 60 |
+
An example of passing multiple dictionaries
|
| 61 |
+
|
| 62 |
+
.. code-block:: python
|
| 63 |
+
|
| 64 |
+
a = (
|
| 65 |
+
{"weight": torch.ones(1, 1)},
|
| 66 |
+
{"buffer": torch.zeros(1)},
|
| 67 |
+
) # two separate dictionaries
|
| 68 |
+
mod = nn.Bar(1, 1) # return self.weight @ x + self.buffer
|
| 69 |
+
print(mod.weight) # tensor(...)
|
| 70 |
+
print(mod.buffer) # tensor(...)
|
| 71 |
+
x = torch.randn((1, 1))
|
| 72 |
+
print(x)
|
| 73 |
+
functional_call(mod, a, x) # same as x
|
| 74 |
+
print(mod.weight) # same as before functional_call
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
And here is an example of applying the grad transform over the parameters
|
| 78 |
+
of a model.
|
| 79 |
+
|
| 80 |
+
.. code-block:: python
|
| 81 |
+
|
| 82 |
+
import torch
|
| 83 |
+
import torch.nn as nn
|
| 84 |
+
from torch.func import functional_call, grad
|
| 85 |
+
|
| 86 |
+
x = torch.randn(4, 3)
|
| 87 |
+
t = torch.randn(4, 3)
|
| 88 |
+
model = nn.Linear(3, 3)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def compute_loss(params, x, t):
|
| 92 |
+
y = functional_call(model, params, x)
|
| 93 |
+
return nn.functional.mse_loss(y, t)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
grad_weights = grad(compute_loss)(dict(model.named_parameters()), x, t)
|
| 97 |
+
|
| 98 |
+
.. note:: If the user does not need grad tracking outside of grad transforms, they can detach all of the
|
| 99 |
+
parameters for better performance and memory usage
|
| 100 |
+
|
| 101 |
+
Example::
|
| 102 |
+
|
| 103 |
+
>>> detached_params = {k: v.detach() for k, v in model.named_parameters()}
|
| 104 |
+
>>> grad_weights = grad(compute_loss)(detached_params, x, t)
|
| 105 |
+
>>> grad_weights.grad_fn # None--it's not tracking gradients outside of grad
|
| 106 |
+
|
| 107 |
+
This means that the user cannot call ``grad_weight.backward()``. However, if they don't need autograd tracking
|
| 108 |
+
outside of the transforms, this will result in less memory usage and faster speeds.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
module (torch.nn.Module): the module to call
|
| 112 |
+
parameters_and_buffer_dicts (Dict[str, Tensor] or tuple of Dict[str, Tensor]): the parameters that will be used in
|
| 113 |
+
the module call. If given a tuple of dictionaries, they must have distinct keys so that all dictionaries can
|
| 114 |
+
be used together
|
| 115 |
+
args (Any or tuple): arguments to be passed to the module call. If not a tuple, considered a single argument.
|
| 116 |
+
kwargs (dict): keyword arguments to be passed to the module call
|
| 117 |
+
tie_weights (bool, optional): If True, then parameters and buffers tied in the original model will be treated as
|
| 118 |
+
tied in the reparameterized version. Therefore, if True and different values are passed for the tied
|
| 119 |
+
parameters and buffers, it will error. If False, it will not respect the originally tied parameters and
|
| 120 |
+
buffers unless the values passed for both weights are the same. Default: True.
|
| 121 |
+
strict (bool, optional): If True, then the parameters and buffers passed in must match the parameters and
|
| 122 |
+
buffers in the original module. Therefore, if True and there are any missing or unexpected keys, it will
|
| 123 |
+
error. Default: False.
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
Any: the result of calling ``module``.
|
| 127 |
+
"""
|
| 128 |
+
if isinstance(parameter_and_buffer_dicts, dict):
|
| 129 |
+
parameters_and_buffers = parameter_and_buffer_dicts
|
| 130 |
+
elif isinstance(parameter_and_buffer_dicts, Sequence):
|
| 131 |
+
if not all(isinstance(d, dict) for d in parameter_and_buffer_dicts):
|
| 132 |
+
raise ValueError(
|
| 133 |
+
"Expected all elements of parameter_and_buffer_dicts to be dictionaries"
|
| 134 |
+
)
|
| 135 |
+
all_keys = [k for d in parameter_and_buffer_dicts for k in d]
|
| 136 |
+
all_keys_counter: dict[str, int] = {}
|
| 137 |
+
for k in all_keys:
|
| 138 |
+
v = all_keys_counter.get(k, 0)
|
| 139 |
+
all_keys_counter[k] = v + 1
|
| 140 |
+
repeated_keys = [key for key, n in all_keys_counter.items() if n > 1]
|
| 141 |
+
if len(repeated_keys) > 0:
|
| 142 |
+
raise ValueError(
|
| 143 |
+
f"{repeated_keys} appeared in multiple dictionaries; behavior of functional call is ambiguous"
|
| 144 |
+
)
|
| 145 |
+
parameters_and_buffers = {
|
| 146 |
+
k: v for d in parameter_and_buffer_dicts for k, v in d.items()
|
| 147 |
+
}
|
| 148 |
+
else:
|
| 149 |
+
raise ValueError(
|
| 150 |
+
f"Expected parameter_and_buffer_dicts to be a dict, or a list/tuple of dicts, "
|
| 151 |
+
f"but got {type(parameter_and_buffer_dicts)}"
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
return nn.utils.stateless._functional_call(
|
| 155 |
+
module,
|
| 156 |
+
parameters_and_buffers,
|
| 157 |
+
args,
|
| 158 |
+
kwargs,
|
| 159 |
+
tie_weights=tie_weights,
|
| 160 |
+
strict=strict,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@exposed_in("torch.func")
|
| 165 |
+
def stack_module_state(
|
| 166 |
+
models: Sequence[nn.Module] | nn.ModuleList,
|
| 167 |
+
) -> tuple[dict[str, Any], dict[str, Any]]:
|
| 168 |
+
"""stack_module_state(models) -> params, buffers
|
| 169 |
+
|
| 170 |
+
Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`.
|
| 171 |
+
|
| 172 |
+
Given a list of ``M`` ``nn.Modules`` of the same class, returns two dictionaries
|
| 173 |
+
that stack all of their parameters and buffers together, indexed by name.
|
| 174 |
+
The stacked parameters are optimizable (i.e. they are new leaf nodes in the
|
| 175 |
+
autograd history that are unrelated to the original parameters and can be
|
| 176 |
+
passed directly to an optimizer).
|
| 177 |
+
|
| 178 |
+
Here's an example of how to ensemble over a very simple model:
|
| 179 |
+
|
| 180 |
+
.. code-block:: python
|
| 181 |
+
|
| 182 |
+
num_models = 5
|
| 183 |
+
batch_size = 64
|
| 184 |
+
in_features, out_features = 3, 3
|
| 185 |
+
models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)]
|
| 186 |
+
data = torch.randn(batch_size, 3)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def wrapper(params, buffers, data):
|
| 190 |
+
return torch.func.functional_call(models[0], (params, buffers), data)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
params, buffers = stack_module_state(models)
|
| 194 |
+
output = vmap(wrapper, (0, 0, None))(params, buffers, data)
|
| 195 |
+
|
| 196 |
+
assert output.shape == (num_models, batch_size, out_features)
|
| 197 |
+
|
| 198 |
+
When there's submodules, this follows state dict naming conventions
|
| 199 |
+
|
| 200 |
+
.. code-block:: python
|
| 201 |
+
|
| 202 |
+
import torch.nn as nn
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class Foo(nn.Module):
|
| 206 |
+
def __init__(self, in_features, out_features):
|
| 207 |
+
super().__init__()
|
| 208 |
+
hidden = 4
|
| 209 |
+
self.l1 = nn.Linear(in_features, hidden)
|
| 210 |
+
self.l2 = nn.Linear(hidden, out_features)
|
| 211 |
+
|
| 212 |
+
def forward(self, x):
|
| 213 |
+
return self.l2(self.l1(x))
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
num_models = 5
|
| 217 |
+
in_features, out_features = 3, 3
|
| 218 |
+
models = [Foo(in_features, out_features) for i in range(num_models)]
|
| 219 |
+
params, buffers = stack_module_state(models)
|
| 220 |
+
print(list(params.keys())) # "l1.weight", "l1.bias", "l2.weight", "l2.bias"
|
| 221 |
+
|
| 222 |
+
.. warning::
|
| 223 |
+
All of the modules being stacked together must be the same (except for
|
| 224 |
+
the values of their parameters/buffers). For example, they should be in the
|
| 225 |
+
same mode (training vs eval).
|
| 226 |
+
"""
|
| 227 |
+
if len(models) == 0:
|
| 228 |
+
raise RuntimeError("stack_module_state: Expected at least one model, got 0.")
|
| 229 |
+
if not (all(m.training for m in models) or all(not m.training for m in models)):
|
| 230 |
+
raise RuntimeError(
|
| 231 |
+
"stack_module_state: Expected all models to have the same training/eval mode."
|
| 232 |
+
)
|
| 233 |
+
model0_typ = type(models[0])
|
| 234 |
+
if not all(type(m) is model0_typ for m in models):
|
| 235 |
+
raise RuntimeError(
|
| 236 |
+
"stack_module_state: Expected all models to be of the same class."
|
| 237 |
+
)
|
| 238 |
+
all_params = [dict(model.named_parameters()) for model in models]
|
| 239 |
+
params = {
|
| 240 |
+
k: construct_stacked_leaf(tuple(params[k] for params in all_params), k)
|
| 241 |
+
for k in all_params[0]
|
| 242 |
+
}
|
| 243 |
+
all_buffers = [dict(model.named_buffers()) for model in models]
|
| 244 |
+
buffers = {
|
| 245 |
+
k: construct_stacked_leaf(tuple(buffers[k] for buffers in all_buffers), k)
|
| 246 |
+
for k in all_buffers[0]
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
return params, buffers
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def construct_stacked_leaf(
|
| 253 |
+
tensors: tuple[Tensor, ...] | list[Tensor], name: str
|
| 254 |
+
) -> Tensor:
|
| 255 |
+
all_requires_grad = all(t.requires_grad for t in tensors)
|
| 256 |
+
none_requires_grad = all(not t.requires_grad for t in tensors)
|
| 257 |
+
if not all_requires_grad and not none_requires_grad:
|
| 258 |
+
raise RuntimeError(
|
| 259 |
+
f"Expected {name} from each model to have the same .requires_grad"
|
| 260 |
+
)
|
| 261 |
+
result = torch.stack(tensors)
|
| 262 |
+
if all_requires_grad:
|
| 263 |
+
result = result.detach().requires_grad_()
|
| 264 |
+
return result
|
venv/lib/python3.14/site-packages/torch/_functorch/fx_minifier.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
from functools import partial, wraps
|
| 9 |
+
from typing import Any, TYPE_CHECKING
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.fx as fx
|
| 13 |
+
from torch.hub import tqdm
|
| 14 |
+
from torch.multiprocessing.reductions import StorageWeakRef
|
| 15 |
+
from torch.utils._content_store import ContentStoreWriter
|
| 16 |
+
|
| 17 |
+
from .compile_utils import get_outputs, get_placeholders
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from collections.abc import Callable, Sequence
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
is_tuple = object()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class LoadTensorMeta:
|
| 29 |
+
size: tuple[int, ...]
|
| 30 |
+
stride: tuple[int, ...]
|
| 31 |
+
dtype: torch.dtype
|
| 32 |
+
device: torch.device
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class ConcreteProp(torch.fx.Interpreter):
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
mod: fx.GraphModule,
|
| 39 |
+
*,
|
| 40 |
+
writer: ContentStoreWriter | None = None,
|
| 41 |
+
skip_offload: bool = False,
|
| 42 |
+
) -> None:
|
| 43 |
+
super().__init__(mod)
|
| 44 |
+
self.writer = writer
|
| 45 |
+
self.skip_offload = skip_offload
|
| 46 |
+
self.seen_storages: set[StorageWeakRef] = set()
|
| 47 |
+
self.pbar: Any = None
|
| 48 |
+
|
| 49 |
+
def run_node(self, n: fx.Node) -> Any:
|
| 50 |
+
self.pbar.update(1)
|
| 51 |
+
r = super().run_node(n)
|
| 52 |
+
name = n.name
|
| 53 |
+
|
| 54 |
+
if isinstance(r, torch.Tensor):
|
| 55 |
+
if self.writer is None:
|
| 56 |
+
n.meta["concrete_value"] = r
|
| 57 |
+
else:
|
| 58 |
+
if StorageWeakRef(r.untyped_storage()) in self.seen_storages:
|
| 59 |
+
# Refuse to offload tensors which alias other live
|
| 60 |
+
# tensors, because this will violate operator contracts
|
| 61 |
+
n.meta["concrete_value"] = None
|
| 62 |
+
else:
|
| 63 |
+
if not self.skip_offload:
|
| 64 |
+
self.writer.write_tensor(os.path.join("eager", name), r)
|
| 65 |
+
n.meta["concrete_value"] = LoadTensorMeta(
|
| 66 |
+
r.size(), r.stride(), r.dtype, r.device
|
| 67 |
+
)
|
| 68 |
+
self.seen_storages.add(StorageWeakRef(r.untyped_storage()))
|
| 69 |
+
else:
|
| 70 |
+
n.meta["concrete_value"] = is_tuple
|
| 71 |
+
|
| 72 |
+
return r
|
| 73 |
+
|
| 74 |
+
def propagate(self, *args: Any) -> Any:
|
| 75 |
+
mod = self.module
|
| 76 |
+
if not isinstance(mod, fx.GraphModule):
|
| 77 |
+
raise AssertionError(f"expected fx.GraphModule, got {type(mod)}")
|
| 78 |
+
with tqdm(
|
| 79 |
+
desc="Saving intermediates for delta debugging",
|
| 80 |
+
total=len(mod.graph.nodes),
|
| 81 |
+
disable=self.writer is None,
|
| 82 |
+
) as pbar:
|
| 83 |
+
self.pbar = pbar
|
| 84 |
+
r = super().run(*args)
|
| 85 |
+
if not self.skip_offload:
|
| 86 |
+
pbar.set_description(
|
| 87 |
+
"Saved! To skip next time, run with --skip-saving-eager-intermediates"
|
| 88 |
+
)
|
| 89 |
+
return r
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def is_load_tensor_node(node: fx.Node) -> bool:
|
| 93 |
+
return (
|
| 94 |
+
node.op == "call_function"
|
| 95 |
+
and node.target is torch.ops.debugprims.load_tensor.default
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# inplace modifies node/inps
|
| 100 |
+
def _convert_node_to_placeholder(
|
| 101 |
+
graph: fx.Graph, node: fx.Node, inps: list[torch.Tensor]
|
| 102 |
+
) -> bool:
|
| 103 |
+
if node.op == "output" or node.op == "placeholder":
|
| 104 |
+
return False
|
| 105 |
+
|
| 106 |
+
if is_load_tensor_node(node):
|
| 107 |
+
return False
|
| 108 |
+
|
| 109 |
+
concrete_val = node.meta.get("concrete_value", None)
|
| 110 |
+
|
| 111 |
+
if isinstance(concrete_val, torch.Tensor):
|
| 112 |
+
node.op = "placeholder"
|
| 113 |
+
node.target = node.name
|
| 114 |
+
node.args = ()
|
| 115 |
+
node.kwargs = {}
|
| 116 |
+
|
| 117 |
+
inps.append(concrete_val)
|
| 118 |
+
return True
|
| 119 |
+
|
| 120 |
+
elif concrete_val is None:
|
| 121 |
+
return False
|
| 122 |
+
|
| 123 |
+
elif concrete_val is is_tuple:
|
| 124 |
+
r = False
|
| 125 |
+
for tuple_user in list(node.users):
|
| 126 |
+
r = _convert_node_to_placeholder(graph, tuple_user, inps) or r
|
| 127 |
+
# NB: We must not erase the node at this point, because
|
| 128 |
+
# we are iterating over the nodes and this would change
|
| 129 |
+
# the iteration order
|
| 130 |
+
# graph.erase_node(node)
|
| 131 |
+
return r
|
| 132 |
+
|
| 133 |
+
elif isinstance(concrete_val, LoadTensorMeta):
|
| 134 |
+
node.op = "call_function"
|
| 135 |
+
node.target = torch.ops.debugprims.load_tensor.default
|
| 136 |
+
node.args = (
|
| 137 |
+
os.path.join("eager", node.name),
|
| 138 |
+
concrete_val.size,
|
| 139 |
+
concrete_val.stride,
|
| 140 |
+
)
|
| 141 |
+
node.kwargs = {
|
| 142 |
+
"device": concrete_val.device,
|
| 143 |
+
"dtype": concrete_val.dtype,
|
| 144 |
+
}
|
| 145 |
+
return True
|
| 146 |
+
|
| 147 |
+
return False
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def create_minified_hlo_graph(
|
| 151 |
+
minified_fx_graph: fx.GraphModule, inputs: Sequence[torch.Tensor]
|
| 152 |
+
) -> None:
|
| 153 |
+
"""
|
| 154 |
+
Takes minified FX graph as primary input, and ports it to HLO via StableHLO
|
| 155 |
+
Provides minified HLO graph as output, and archive them to local directory
|
| 156 |
+
"""
|
| 157 |
+
hlo_dir = f"{os.getcwd()}/hlo_files"
|
| 158 |
+
os.makedirs(hlo_dir, exist_ok=True)
|
| 159 |
+
|
| 160 |
+
from torch_xla.stablehlo import save_torch_model_as_stablehlo
|
| 161 |
+
|
| 162 |
+
save_torch_model_as_stablehlo(minified_fx_graph, inputs, hlo_dir)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def dump_state(fx_g: fx.GraphModule, inps: Sequence[torch.Tensor]) -> None:
|
| 166 |
+
print(
|
| 167 |
+
f"""
|
| 168 |
+
# Working Repro with {len(fx_g.graph.nodes)} nodes
|
| 169 |
+
inps = {[(i.shape, i.dtype, i.device.type) for i in inps]}
|
| 170 |
+
inps = [torch.zeros(())] + [torch.ones(shape, dtype=dtype, device=device) for (shape, dtype, device) in inps]
|
| 171 |
+
{fx_g.code}
|
| 172 |
+
"""
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def is_power_of_two(n: int) -> bool:
|
| 177 |
+
if n == 0:
|
| 178 |
+
return False
|
| 179 |
+
return (n & (n - 1)) == 0
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@dataclass
|
| 183 |
+
class ReproState:
|
| 184 |
+
graph: fx.Graph
|
| 185 |
+
inps: Sequence[torch.Tensor]
|
| 186 |
+
|
| 187 |
+
def __post_init__(self) -> None:
|
| 188 |
+
ph_nodes = get_placeholders(self.graph)
|
| 189 |
+
if len(ph_nodes) != len(self.inps):
|
| 190 |
+
raise AssertionError(
|
| 191 |
+
f"len(ph_nodes)={len(ph_nodes)} != len(self.inps)={len(self.inps)}"
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def minifier(
|
| 196 |
+
fail_f: fx.GraphModule,
|
| 197 |
+
inps: Sequence[torch.Tensor],
|
| 198 |
+
module_fails: Callable[[fx.GraphModule, Sequence[torch.Tensor]], bool],
|
| 199 |
+
dump_state: Callable[[fx.GraphModule, Sequence[torch.Tensor]], None] = dump_state,
|
| 200 |
+
*,
|
| 201 |
+
save_dir: str | None = None,
|
| 202 |
+
offload_to_disk: bool = False,
|
| 203 |
+
skip_offload: bool = False,
|
| 204 |
+
skip_sanity: bool = False,
|
| 205 |
+
max_granularity: int | None = None,
|
| 206 |
+
) -> tuple[fx.GraphModule, Sequence[torch.Tensor]]:
|
| 207 |
+
"""
|
| 208 |
+
Minimizes a FX graph with given inputs, such that the resulting FX graph still returns True for module_fails.
|
| 209 |
+
|
| 210 |
+
Does 2 main strategies:
|
| 211 |
+
1. Truncates suffix: Removes some suffix from the graph and sets a new output.
|
| 212 |
+
2. Delta Debugging: Tries replacing half of the graph with inputs. If fails,
|
| 213 |
+
tries replacing quarter of the graph, etc.
|
| 214 |
+
|
| 215 |
+
>>> # xdoctest: +SKIP(failing)
|
| 216 |
+
>>> failing_function = fx.symbolic_trace(f)
|
| 217 |
+
>>> minimize(failing_function, [torch.randn(5)], lambda fx_g, inps: fx_g(*inps))
|
| 218 |
+
|
| 219 |
+
note: module_fails returns True if it fails.
|
| 220 |
+
"""
|
| 221 |
+
|
| 222 |
+
failing_graph = fail_f.graph
|
| 223 |
+
cur_size = len(failing_graph.nodes)
|
| 224 |
+
|
| 225 |
+
if max_granularity is not None and not is_power_of_two(max_granularity):
|
| 226 |
+
raise RuntimeError(f"max_granularity {max_granularity} not power of two")
|
| 227 |
+
|
| 228 |
+
num_queries = 0
|
| 229 |
+
|
| 230 |
+
def deepcopy_fx_graph(fx_graph: fx.Graph) -> fx.Graph:
|
| 231 |
+
return fx.GraphModule(fail_f, copy.deepcopy(fx_graph)).graph
|
| 232 |
+
|
| 233 |
+
def graph_fails(graph: fx.Graph, inps: Sequence[torch.Tensor]) -> bool:
|
| 234 |
+
nonlocal num_queries
|
| 235 |
+
graph = copy.deepcopy(graph)
|
| 236 |
+
num_queries += 1
|
| 237 |
+
mod = fx.GraphModule(fail_f, graph)
|
| 238 |
+
mod.graph.lint()
|
| 239 |
+
return module_fails(mod, inps)
|
| 240 |
+
|
| 241 |
+
writer = None
|
| 242 |
+
if offload_to_disk:
|
| 243 |
+
if save_dir is None:
|
| 244 |
+
raise AssertionError("save_dir must not be None when offload_to_disk=True")
|
| 245 |
+
writer = ContentStoreWriter(save_dir)
|
| 246 |
+
|
| 247 |
+
ConcreteProp(fail_f, writer=writer, skip_offload=skip_offload).propagate(*inps)
|
| 248 |
+
if not skip_sanity and not graph_fails(failing_graph, inps):
|
| 249 |
+
raise RuntimeError("Input graph did not fail the tester")
|
| 250 |
+
print(f"Started off with {cur_size} nodes", file=sys.stderr)
|
| 251 |
+
|
| 252 |
+
def _register_strategy(
|
| 253 |
+
strategy: Callable[[fx.Graph, Sequence[torch.Tensor], int], ReproState | None],
|
| 254 |
+
name: str,
|
| 255 |
+
) -> Callable[[ReproState, int], ReproState | None]:
|
| 256 |
+
@wraps(strategy)
|
| 257 |
+
def new_func(old_state: ReproState, granularity: int = 1) -> ReproState | None:
|
| 258 |
+
print(file=sys.stderr)
|
| 259 |
+
print(
|
| 260 |
+
f"Strategy: {name} (G: {granularity}) "
|
| 261 |
+
f"({len(old_state.graph.nodes)} nodes, {len(old_state.inps)} inputs)",
|
| 262 |
+
file=sys.stderr,
|
| 263 |
+
)
|
| 264 |
+
new_state = strategy(
|
| 265 |
+
deepcopy_fx_graph(old_state.graph), list(old_state.inps), granularity
|
| 266 |
+
)
|
| 267 |
+
if new_state is not None:
|
| 268 |
+
new_nodes = len(new_state.graph.nodes)
|
| 269 |
+
old_nodes = len(old_state.graph.nodes)
|
| 270 |
+
new_inps = len(new_state.inps)
|
| 271 |
+
old_inps = len(old_state.inps)
|
| 272 |
+
new_outs = len(get_outputs(new_state.graph))
|
| 273 |
+
old_outs = len(get_outputs(old_state.graph))
|
| 274 |
+
progress_made = False
|
| 275 |
+
if new_nodes < old_nodes:
|
| 276 |
+
progress_made = True
|
| 277 |
+
print(
|
| 278 |
+
f"SUCCESS: Went from {old_nodes} to {new_nodes} nodes",
|
| 279 |
+
file=sys.stderr,
|
| 280 |
+
)
|
| 281 |
+
if new_inps > old_inps:
|
| 282 |
+
progress_made = True
|
| 283 |
+
print(
|
| 284 |
+
f"SUCCESS: Went from {old_inps} to {new_inps} inputs",
|
| 285 |
+
file=sys.stderr,
|
| 286 |
+
)
|
| 287 |
+
if new_outs < old_outs:
|
| 288 |
+
progress_made = True
|
| 289 |
+
print(
|
| 290 |
+
f"SUCCESS: Went from {old_outs} to {new_outs} outputs",
|
| 291 |
+
file=sys.stderr,
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
if not progress_made:
|
| 295 |
+
raise RuntimeError("Success raised but no progress made?")
|
| 296 |
+
|
| 297 |
+
if not graph_fails(new_state.graph, new_state.inps):
|
| 298 |
+
print(
|
| 299 |
+
"WARNING: Something went wrong, not applying this minification",
|
| 300 |
+
file=sys.stderr,
|
| 301 |
+
)
|
| 302 |
+
return None
|
| 303 |
+
return new_state
|
| 304 |
+
else:
|
| 305 |
+
print(f"FAIL: {name}", file=sys.stderr)
|
| 306 |
+
return None
|
| 307 |
+
|
| 308 |
+
return new_func
|
| 309 |
+
|
| 310 |
+
def register_strategy(
|
| 311 |
+
name: str,
|
| 312 |
+
) -> Callable[
|
| 313 |
+
[Callable[[fx.Graph, Sequence[torch.Tensor], int], ReproState | None]],
|
| 314 |
+
Callable[[ReproState, int], ReproState | None],
|
| 315 |
+
]:
|
| 316 |
+
return partial(_register_strategy, name=name)
|
| 317 |
+
|
| 318 |
+
@register_strategy("Truncate suffix")
|
| 319 |
+
def remove_suffix(
|
| 320 |
+
cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
|
| 321 |
+
) -> ReproState | None:
|
| 322 |
+
tested: set[int] = set()
|
| 323 |
+
new_graph = fx.Graph()
|
| 324 |
+
env: dict[fx.Node, fx.Node] = {}
|
| 325 |
+
for idx, node in enumerate(cur_graph.nodes):
|
| 326 |
+
new_node = new_graph.node_copy(node, lambda x: env[x])
|
| 327 |
+
if node.op not in ["placeholder", "output"]:
|
| 328 |
+
# If idx is divisible by (granularity * 2), it would have been checked already.
|
| 329 |
+
if (
|
| 330 |
+
idx % granularity == 0
|
| 331 |
+
and (idx % (granularity * 2) != 0)
|
| 332 |
+
and idx not in tested
|
| 333 |
+
):
|
| 334 |
+
output_node = new_graph.output((new_node,))
|
| 335 |
+
if len(new_graph.nodes) < len(cur_graph.nodes) and graph_fails(
|
| 336 |
+
new_graph, cur_inps
|
| 337 |
+
):
|
| 338 |
+
return ReproState(new_graph, cur_inps)
|
| 339 |
+
else:
|
| 340 |
+
tested.add(idx)
|
| 341 |
+
new_graph.erase_node(output_node)
|
| 342 |
+
env[node] = new_node
|
| 343 |
+
return None
|
| 344 |
+
|
| 345 |
+
@register_strategy("Remove outputs")
|
| 346 |
+
def remove_outputs(
|
| 347 |
+
cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
|
| 348 |
+
) -> ReproState | None:
|
| 349 |
+
granularity = max(1, granularity // 2)
|
| 350 |
+
output: fx.Node | None = None
|
| 351 |
+
for idx, node in enumerate(cur_graph.nodes):
|
| 352 |
+
node.idx = idx # type: ignore[attr-defined]
|
| 353 |
+
if node.op == "output":
|
| 354 |
+
output = node
|
| 355 |
+
break
|
| 356 |
+
|
| 357 |
+
if output is None:
|
| 358 |
+
return None
|
| 359 |
+
|
| 360 |
+
if isinstance(output.args[0], fx.Node):
|
| 361 |
+
return None
|
| 362 |
+
|
| 363 |
+
# output.args[0] is a tuple/list of nodes when returning multiple outputs
|
| 364 |
+
output_args_raw = output.args[0]
|
| 365 |
+
if not isinstance(output_args_raw, (list, tuple)):
|
| 366 |
+
raise AssertionError(
|
| 367 |
+
f"expected output_args_raw to be list or tuple, got {type(output_args_raw)}"
|
| 368 |
+
)
|
| 369 |
+
output_args = sorted(
|
| 370 |
+
output_args_raw,
|
| 371 |
+
key=lambda x: x.idx if isinstance(x, fx.Node) else int(1e9), # type: ignore[attr-defined]
|
| 372 |
+
)
|
| 373 |
+
if len(output_args) == 1:
|
| 374 |
+
return None
|
| 375 |
+
|
| 376 |
+
for idx in range(0, len(output_args), granularity):
|
| 377 |
+
output.args = (output_args[:idx] + output_args[idx + granularity :],)
|
| 378 |
+
if graph_fails(cur_graph, cur_inps):
|
| 379 |
+
return ReproState(cur_graph, cur_inps)
|
| 380 |
+
return None
|
| 381 |
+
|
| 382 |
+
def remove_unused_inputs_unchecked(cur_state: ReproState) -> ReproState | None:
|
| 383 |
+
cur_graph = cur_state.graph
|
| 384 |
+
cur_inps = cur_state.inps
|
| 385 |
+
ph_nodes = list(get_placeholders(cur_graph))
|
| 386 |
+
if len(ph_nodes) != len(cur_inps):
|
| 387 |
+
raise AssertionError(
|
| 388 |
+
f"len(ph_nodes)={len(ph_nodes)} != len(cur_inps)={len(cur_inps)}"
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
new_inps: list[torch.Tensor] = []
|
| 392 |
+
for idx in range(len(ph_nodes)):
|
| 393 |
+
if len(ph_nodes[idx].users) == 0:
|
| 394 |
+
cur_graph.erase_node(ph_nodes[idx])
|
| 395 |
+
else:
|
| 396 |
+
new_inps.append(cur_inps[idx])
|
| 397 |
+
if len(new_inps) < len(cur_inps):
|
| 398 |
+
return ReproState(cur_graph, new_inps)
|
| 399 |
+
return None
|
| 400 |
+
|
| 401 |
+
def remove_unused_inputs_checked(cur_state: ReproState) -> ReproState | None:
|
| 402 |
+
new_state = remove_unused_inputs_unchecked(cur_state)
|
| 403 |
+
if new_state is not None and graph_fails(new_state.graph, new_state.inps):
|
| 404 |
+
return new_state
|
| 405 |
+
return None
|
| 406 |
+
|
| 407 |
+
def _remove_unused_wrapper(
|
| 408 |
+
cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
|
| 409 |
+
) -> ReproState | None:
|
| 410 |
+
return remove_unused_inputs_checked(ReproState(cur_graph, cur_inps))
|
| 411 |
+
|
| 412 |
+
remove_unused_inputs = register_strategy("Remove unused inputs")(
|
| 413 |
+
_remove_unused_wrapper
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
@register_strategy("Eliminate dead code")
|
| 417 |
+
def eliminate_dead_code(
|
| 418 |
+
cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
|
| 419 |
+
) -> ReproState | None:
|
| 420 |
+
if cur_graph.eliminate_dead_code() and graph_fails(cur_graph, cur_inps):
|
| 421 |
+
return ReproState(cur_graph, cur_inps)
|
| 422 |
+
return None
|
| 423 |
+
|
| 424 |
+
def _consolidate_placeholders(
|
| 425 |
+
cur_graph: fx.Graph, inps: list[torch.Tensor]
|
| 426 |
+
) -> fx.Graph:
|
| 427 |
+
new_graph = fx.Graph()
|
| 428 |
+
env = {}
|
| 429 |
+
seen_non_placeholder = False
|
| 430 |
+
|
| 431 |
+
# Move all placeholders to the front; also, if any load_tensor
|
| 432 |
+
# is at the front, convert it into an input (because it can be live
|
| 433 |
+
# all the time)
|
| 434 |
+
for node in cur_graph.nodes:
|
| 435 |
+
if node.op == "placeholder":
|
| 436 |
+
new_node = new_graph.node_copy(node, lambda x: env[x])
|
| 437 |
+
env[node] = new_node
|
| 438 |
+
elif not seen_non_placeholder and is_load_tensor_node(node):
|
| 439 |
+
new_node = new_graph.placeholder(node.name)
|
| 440 |
+
env[node] = new_node
|
| 441 |
+
inps.append(
|
| 442 |
+
torch.ops.debugprims.load_tensor.default(*node.args, **node.kwargs)
|
| 443 |
+
)
|
| 444 |
+
else:
|
| 445 |
+
seen_non_placeholder = True
|
| 446 |
+
|
| 447 |
+
# Move everyone else
|
| 448 |
+
for node in cur_graph.nodes:
|
| 449 |
+
if node not in env:
|
| 450 |
+
new_node = new_graph.node_copy(node, lambda x: env[x])
|
| 451 |
+
env[node] = new_node
|
| 452 |
+
return new_graph
|
| 453 |
+
|
| 454 |
+
@register_strategy("Delta Debugging")
|
| 455 |
+
def delta_debugging(
|
| 456 |
+
cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
|
| 457 |
+
) -> ReproState | None:
|
| 458 |
+
num_nodes = len(cur_graph.nodes)
|
| 459 |
+
for start_range in range(0, num_nodes, granularity):
|
| 460 |
+
is_removing = False
|
| 461 |
+
new_graph = deepcopy_fx_graph(cur_graph)
|
| 462 |
+
new_inps = list(cur_inps[:])
|
| 463 |
+
end_range = min(num_nodes, start_range + granularity)
|
| 464 |
+
for idx in range(start_range, end_range):
|
| 465 |
+
new_node = list(new_graph.nodes)[idx]
|
| 466 |
+
if _convert_node_to_placeholder(new_graph, new_node, new_inps):
|
| 467 |
+
is_removing = True
|
| 468 |
+
if not is_removing:
|
| 469 |
+
continue
|
| 470 |
+
new_graph.eliminate_dead_code()
|
| 471 |
+
new_graph = _consolidate_placeholders(new_graph, new_inps)
|
| 472 |
+
new_state = remove_unused_inputs_unchecked(ReproState(new_graph, new_inps))
|
| 473 |
+
if new_state is None:
|
| 474 |
+
new_state = ReproState(new_graph, new_inps)
|
| 475 |
+
if graph_fails(new_state.graph, new_state.inps):
|
| 476 |
+
return ReproState(new_state.graph, new_state.inps)
|
| 477 |
+
|
| 478 |
+
return None
|
| 479 |
+
|
| 480 |
+
@register_strategy("Consolidate Inputs")
|
| 481 |
+
def consolidate_inputs(
|
| 482 |
+
cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
|
| 483 |
+
) -> ReproState | None:
|
| 484 |
+
old_len = len(cur_inps)
|
| 485 |
+
new_inps = list(cur_inps[:])
|
| 486 |
+
cur_graph = _consolidate_placeholders(cur_graph, new_inps)
|
| 487 |
+
if len(cur_inps) > old_len and graph_fails(cur_graph, new_inps):
|
| 488 |
+
return ReproState(cur_graph, new_inps)
|
| 489 |
+
return None
|
| 490 |
+
|
| 491 |
+
failing_state = ReproState(failing_graph, inps)
|
| 492 |
+
|
| 493 |
+
def try_granularity(
|
| 494 |
+
failing_state: ReproState, granularity: int, use_non_granular: bool
|
| 495 |
+
) -> ReproState | None:
|
| 496 |
+
print(f"Trying granularity {granularity}", file=sys.stderr)
|
| 497 |
+
|
| 498 |
+
strategies = []
|
| 499 |
+
num_nodes = len(failing_state.graph.nodes)
|
| 500 |
+
num_outputs = len(get_outputs(failing_state.graph))
|
| 501 |
+
if num_outputs > num_nodes // 2:
|
| 502 |
+
strategies += [remove_outputs]
|
| 503 |
+
|
| 504 |
+
if use_non_granular:
|
| 505 |
+
strategies += [
|
| 506 |
+
eliminate_dead_code,
|
| 507 |
+
remove_unused_inputs,
|
| 508 |
+
consolidate_inputs,
|
| 509 |
+
]
|
| 510 |
+
|
| 511 |
+
strategies += [remove_suffix, delta_debugging]
|
| 512 |
+
|
| 513 |
+
for strategy in strategies:
|
| 514 |
+
new_state = strategy(failing_state, granularity)
|
| 515 |
+
if new_state is not None:
|
| 516 |
+
return new_state
|
| 517 |
+
return None
|
| 518 |
+
|
| 519 |
+
while True:
|
| 520 |
+
dump_state(fx.GraphModule(fail_f, failing_state.graph), failing_state.inps)
|
| 521 |
+
granularity = int(2 ** (math.floor(math.log2(len(failing_state.graph.nodes)))))
|
| 522 |
+
if max_granularity is not None:
|
| 523 |
+
granularity = min(max_granularity, granularity)
|
| 524 |
+
new_state = try_granularity(failing_state, granularity, use_non_granular=True)
|
| 525 |
+
if new_state is not None:
|
| 526 |
+
failing_state = new_state
|
| 527 |
+
continue
|
| 528 |
+
|
| 529 |
+
granularity //= 2
|
| 530 |
+
has_progress = False
|
| 531 |
+
while granularity >= 1:
|
| 532 |
+
new_state = try_granularity(
|
| 533 |
+
failing_state, granularity, use_non_granular=False
|
| 534 |
+
)
|
| 535 |
+
if new_state is not None:
|
| 536 |
+
failing_state = new_state
|
| 537 |
+
has_progress = True
|
| 538 |
+
break
|
| 539 |
+
granularity //= 2
|
| 540 |
+
if has_progress:
|
| 541 |
+
continue
|
| 542 |
+
|
| 543 |
+
new_state = remove_outputs(failing_state, 1)
|
| 544 |
+
if new_state is not None:
|
| 545 |
+
failing_state = new_state
|
| 546 |
+
continue
|
| 547 |
+
|
| 548 |
+
break
|
| 549 |
+
|
| 550 |
+
if not graph_fails(failing_state.graph, failing_state.inps):
|
| 551 |
+
raise RuntimeError("Uh oh, something went wrong :( Final graph is not failing")
|
| 552 |
+
|
| 553 |
+
print(f"Made {num_queries} queries", file=sys.stderr)
|
| 554 |
+
failing_fx = fx.GraphModule(fail_f, failing_state.graph)
|
| 555 |
+
|
| 556 |
+
# If XLA debugging environment is enabled, create minified HLO graph as well
|
| 557 |
+
if "XLA_HLO_DEBUG" in os.environ:
|
| 558 |
+
create_minified_hlo_graph(failing_fx, failing_state.inps)
|
| 559 |
+
|
| 560 |
+
dump_state(failing_fx, failing_state.inps)
|
| 561 |
+
print("Wrote minimal repro out to repro.py", file=sys.stderr)
|
| 562 |
+
return failing_fx, failing_state.inps
|
venv/lib/python3.14/site-packages/torch/_functorch/make_functional.py
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import copy
|
| 10 |
+
from typing import Any, NoReturn, TYPE_CHECKING
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from torch import Tensor
|
| 15 |
+
from torch.nn.utils._named_member_accessor import NamedMemberAccessor
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 20 |
+
|
| 21 |
+
# Utilities to make nn.Module "functional"
|
| 22 |
+
# In particular the goal is to be able to provide a function that takes as input
|
| 23 |
+
# the parameters and evaluate the nn.Module using fixed inputs.
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def raise_parameter_tying_error() -> NoReturn:
|
| 27 |
+
raise RuntimeError(
|
| 28 |
+
"make_functional(module): we don't yet support models that "
|
| 29 |
+
"do parameter tying (also sometimes known as weight sharing). "
|
| 30 |
+
"Please try to rewrite your model by replacing all instances of the "
|
| 31 |
+
"tied parameter with another and/or comment your support in "
|
| 32 |
+
"https://github.com/pytorch/functorch/issues/446"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def create_names_map(
|
| 37 |
+
named_params: dict[str, Tensor] | Iterable[tuple[str, Tensor]],
|
| 38 |
+
tied_named_params: dict[str, Tensor] | Iterable[tuple[str, Tensor]],
|
| 39 |
+
) -> dict[str, list[str]]:
|
| 40 |
+
"""
|
| 41 |
+
named_params is a dictionary of tensors: {'A': A, 'B': B}
|
| 42 |
+
tied_named_params is another dictionary of tensors {'A': A, 'B': B, 'B_tied': B}
|
| 43 |
+
with potentially tied (or 'duplicated') tensors
|
| 44 |
+
|
| 45 |
+
This function creates a mapping from the names in named_params to the
|
| 46 |
+
names in tied_named_params: {'A': ['A'], 'B': ['B', 'B_tied']}.
|
| 47 |
+
"""
|
| 48 |
+
named_params_dict = dict(named_params)
|
| 49 |
+
tied_named_params_dict = dict(tied_named_params)
|
| 50 |
+
|
| 51 |
+
tensors_dict_keys = set(named_params_dict.keys())
|
| 52 |
+
tied_tensors_dict_keys = set(tied_named_params_dict.keys())
|
| 53 |
+
if not tensors_dict_keys.issubset(tied_tensors_dict_keys):
|
| 54 |
+
raise AssertionError(
|
| 55 |
+
f"tensors_dict_keys {tensors_dict_keys} is not a subset of "
|
| 56 |
+
f"tied_tensors_dict_keys {tied_tensors_dict_keys}"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
tensor_to_mapping: dict[Tensor, tuple[str, list[str]]] = {}
|
| 60 |
+
for key, tensor in named_params_dict.items():
|
| 61 |
+
tensor_to_mapping[tensor] = (key, [])
|
| 62 |
+
for key, tensor in tied_named_params_dict.items():
|
| 63 |
+
if tensor not in tensor_to_mapping:
|
| 64 |
+
raise AssertionError(
|
| 65 |
+
f"tensor for key '{key}' not found in tensor_to_mapping"
|
| 66 |
+
)
|
| 67 |
+
tensor_to_mapping[tensor][1].append(key)
|
| 68 |
+
return dict(tensor_to_mapping.values())
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _extract_members(
|
| 72 |
+
mod: nn.Module,
|
| 73 |
+
named_members: Callable[..., Iterable[tuple[str, Tensor]]],
|
| 74 |
+
subclass: Callable[[Tensor], Tensor],
|
| 75 |
+
) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]:
|
| 76 |
+
all_named_members = tuple(named_members(remove_duplicate=False))
|
| 77 |
+
unique_named_members = tuple(named_members(remove_duplicate=True))
|
| 78 |
+
names_map = create_names_map(unique_named_members, all_named_members)
|
| 79 |
+
|
| 80 |
+
# Remove all the members in the model
|
| 81 |
+
# pyrefly: ignore [implicit-any]
|
| 82 |
+
memo = {}
|
| 83 |
+
accessor = NamedMemberAccessor(mod)
|
| 84 |
+
for name, p in all_named_members:
|
| 85 |
+
if p not in memo:
|
| 86 |
+
memo[p] = subclass(torch.empty_like(p, device="meta"))
|
| 87 |
+
replacement = memo[p]
|
| 88 |
+
accessor.set_tensor(name, replacement)
|
| 89 |
+
|
| 90 |
+
if len(unique_named_members) == 0:
|
| 91 |
+
names, params = (), ()
|
| 92 |
+
else:
|
| 93 |
+
names, params = zip(*unique_named_members) # type: ignore[assignment]
|
| 94 |
+
return params, names, names_map
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def extract_weights(
|
| 98 |
+
mod: nn.Module,
|
| 99 |
+
) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]:
|
| 100 |
+
"""
|
| 101 |
+
This function removes all the Parameters from the model and
|
| 102 |
+
return them as a tuple as well as their original attribute names.
|
| 103 |
+
The weights must be re-loaded with `load_weights` before the model
|
| 104 |
+
can be used again.
|
| 105 |
+
Note that this function modifies the model in place and after this
|
| 106 |
+
call, mod.parameters() will be empty.
|
| 107 |
+
"""
|
| 108 |
+
return _extract_members(mod, mod.named_parameters, nn.Parameter)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def extract_buffers(
|
| 112 |
+
mod: nn.Module,
|
| 113 |
+
) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]:
|
| 114 |
+
return _extract_members(mod, mod.named_buffers, lambda x: x)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def load_weights(
|
| 118 |
+
mod: nn.Module,
|
| 119 |
+
names: Sequence[str],
|
| 120 |
+
params: Sequence[Tensor],
|
| 121 |
+
as_params: bool = False,
|
| 122 |
+
) -> None:
|
| 123 |
+
"""
|
| 124 |
+
Reload a set of weights so that `mod` can be used again to perform a forward pass.
|
| 125 |
+
Note that the `params` are regular Tensors (that can have history) and so are left
|
| 126 |
+
as Tensors. This means that mod.parameters() will still be empty after this call.
|
| 127 |
+
"""
|
| 128 |
+
accessor = NamedMemberAccessor(mod)
|
| 129 |
+
if as_params:
|
| 130 |
+
params = [nn.Parameter(p) for p in params]
|
| 131 |
+
accessor.set_tensors(names, params)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _swap_state(
|
| 135 |
+
mod: nn.Module, names_map: dict[str, list[str]], elems: Iterable[Tensor]
|
| 136 |
+
) -> list[Tensor]:
|
| 137 |
+
result: list[Tensor] = []
|
| 138 |
+
accessor = NamedMemberAccessor(mod)
|
| 139 |
+
for (_, attr_names), elem in zip(names_map.items(), elems):
|
| 140 |
+
for i, attr_name in enumerate(attr_names):
|
| 141 |
+
if i == 0:
|
| 142 |
+
result.append(accessor.swap_tensor(attr_name, elem))
|
| 143 |
+
else:
|
| 144 |
+
accessor.set_tensor(attr_name, elem)
|
| 145 |
+
return result
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def load_buffers(
|
| 149 |
+
mod: nn.Module,
|
| 150 |
+
names: Sequence[str],
|
| 151 |
+
buffers: Sequence[Tensor],
|
| 152 |
+
as_params: bool = False,
|
| 153 |
+
) -> None:
|
| 154 |
+
accessor = NamedMemberAccessor(mod)
|
| 155 |
+
accessor.set_tensors(names, buffers)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def load_state(
|
| 159 |
+
model: nn.Module,
|
| 160 |
+
weights: Sequence[Tensor],
|
| 161 |
+
weight_names: Sequence[str],
|
| 162 |
+
buffers: Sequence[Tensor] = (),
|
| 163 |
+
buffer_names: Sequence[str] = (),
|
| 164 |
+
) -> nn.Module:
|
| 165 |
+
"""load_state(model, weights, weight_names, buffers=(), buffer_names=()) -> model
|
| 166 |
+
|
| 167 |
+
load_state takes `weights` and `buffers` and assigns them to the model.
|
| 168 |
+
This is the inverse operation of `make_functional_deprecated_v1`.
|
| 169 |
+
"""
|
| 170 |
+
if len(weight_names) != len(weights):
|
| 171 |
+
raise AssertionError(
|
| 172 |
+
f"len(weight_names)={len(weight_names)} != len(weights)={len(weights)}"
|
| 173 |
+
)
|
| 174 |
+
load_weights(model, weight_names, weights)
|
| 175 |
+
if len(buffers) > 0:
|
| 176 |
+
if len(buffer_names) != len(buffers):
|
| 177 |
+
raise AssertionError(
|
| 178 |
+
f"len(buffer_names)={len(buffer_names)} != len(buffers)={len(buffers)}"
|
| 179 |
+
)
|
| 180 |
+
load_buffers(model, buffer_names, buffers)
|
| 181 |
+
return model
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def make_functional_deprecated_v1(
|
| 185 |
+
model: nn.Module,
|
| 186 |
+
) -> tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]:
|
| 187 |
+
"""make_functional_deprecated_v1(model) -> weights, func, weight_names
|
| 188 |
+
|
| 189 |
+
Given an nn.Module, make_functional_deprecated_v1 extracts the state (weights)
|
| 190 |
+
and returns a functional version of the model, `func`. This makes
|
| 191 |
+
it so that it is possible use transforms over the parameters of
|
| 192 |
+
`model`.
|
| 193 |
+
|
| 194 |
+
`func` can be invoked as follows:
|
| 195 |
+
```
|
| 196 |
+
x = torch.randn(4, 3)
|
| 197 |
+
model = nn.Linear(3, 3)
|
| 198 |
+
weights, func, _ = make_functional_deprecated_v1(model)
|
| 199 |
+
func(weights, (x,))
|
| 200 |
+
```
|
| 201 |
+
|
| 202 |
+
And here is an example of applying the grad transform:
|
| 203 |
+
```
|
| 204 |
+
x = torch.randn(4, 3)
|
| 205 |
+
model = nn.Linear(3, 3)
|
| 206 |
+
weights, _, func = make_functional_deprecated_v1(model)
|
| 207 |
+
grad_weights = grad(func)(weights, (x,))
|
| 208 |
+
```
|
| 209 |
+
|
| 210 |
+
To put the state back into a model, use `load_state`.
|
| 211 |
+
"""
|
| 212 |
+
buffers = list(model.buffers())
|
| 213 |
+
if len(buffers) > 0:
|
| 214 |
+
raise RuntimeError(
|
| 215 |
+
"make_functional_deprecated_v1(model): `model` has buffers. Please use "
|
| 216 |
+
"make_functional_with_buffers_deprecated_v1(model) instead."
|
| 217 |
+
)
|
| 218 |
+
weights, descriptors, _ = extract_weights(model)
|
| 219 |
+
|
| 220 |
+
def fun(weights: tuple[Tensor, ...], data: tuple[Any, ...]) -> Any:
|
| 221 |
+
mutable_model = copy.deepcopy(model)
|
| 222 |
+
load_weights(mutable_model, descriptors, weights)
|
| 223 |
+
return mutable_model(*data)
|
| 224 |
+
|
| 225 |
+
return weights, fun, descriptors
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def make_functional_with_buffers_deprecated_v1(
|
| 229 |
+
model: nn.Module,
|
| 230 |
+
) -> tuple[
|
| 231 |
+
tuple[Tensor, ...],
|
| 232 |
+
tuple[Tensor, ...],
|
| 233 |
+
Callable[..., Any],
|
| 234 |
+
tuple[str, ...],
|
| 235 |
+
tuple[str, ...],
|
| 236 |
+
]:
|
| 237 |
+
"""make_functional_with_buffers_deprecated_v1(model) -> weights, buffers, func, weight_names, buffer_names
|
| 238 |
+
|
| 239 |
+
Given an nn.Module, make_functional_with_buffers_deprecated_v1 extracts the state (weights and buffers)
|
| 240 |
+
and returns a functional version of the model, `func`.
|
| 241 |
+
|
| 242 |
+
`func` can be invoked as follows:
|
| 243 |
+
```
|
| 244 |
+
x = torch.randn(4, 3)
|
| 245 |
+
model = nn.Linear(3, 3)
|
| 246 |
+
weights, buffers, func, _, _ = make_functional_with_buffers_deprecated_v1(model)
|
| 247 |
+
func(weights, buffers, (x,))
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
And here is an example of applying the grad transform:
|
| 251 |
+
```
|
| 252 |
+
x = torch.randn(4, 3)
|
| 253 |
+
model = nn.Linear(3, 3)
|
| 254 |
+
weights, buffers, func, _, _ = make_functional_with_buffers_deprecated_v1(model)
|
| 255 |
+
func(weights, buffers, (x,))
|
| 256 |
+
grad_weights = grad(func)(weights, buffers, (x,))
|
| 257 |
+
```
|
| 258 |
+
|
| 259 |
+
To put the state back into a model, use `load_state`.
|
| 260 |
+
"""
|
| 261 |
+
weights, weight_descriptors, _ = extract_weights(model)
|
| 262 |
+
buffers, buf_descriptors, _ = extract_buffers(model)
|
| 263 |
+
|
| 264 |
+
def fun(
|
| 265 |
+
weights: tuple[Tensor, ...],
|
| 266 |
+
buffers: tuple[Tensor, ...],
|
| 267 |
+
data: tuple[Any, ...],
|
| 268 |
+
) -> Any:
|
| 269 |
+
mutable_model = copy.deepcopy(model)
|
| 270 |
+
load_weights(mutable_model, weight_descriptors, weights)
|
| 271 |
+
load_buffers(mutable_model, buf_descriptors, buffers)
|
| 272 |
+
return mutable_model(*data)
|
| 273 |
+
|
| 274 |
+
return weights, buffers, fun, weight_descriptors, buf_descriptors
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class FunctionalModuleWithBuffers(nn.Module):
|
| 278 |
+
"""
|
| 279 |
+
This is the callable object returned by :func:`make_functional_with_buffers`.
|
| 280 |
+
"""
|
| 281 |
+
|
| 282 |
+
def __init__(
|
| 283 |
+
self,
|
| 284 |
+
stateless_model: nn.Module,
|
| 285 |
+
param_names: tuple[str, ...],
|
| 286 |
+
buffer_names: tuple[str, ...],
|
| 287 |
+
param_names_map: dict[str, list[str]],
|
| 288 |
+
buffer_names_map: dict[str, list[str]],
|
| 289 |
+
) -> None:
|
| 290 |
+
super().__init__()
|
| 291 |
+
self.stateless_model = stateless_model
|
| 292 |
+
self.param_names = param_names
|
| 293 |
+
self.buffer_names = buffer_names
|
| 294 |
+
|
| 295 |
+
self.all_names_map = dict(param_names_map)
|
| 296 |
+
self.all_names_map.update(buffer_names_map)
|
| 297 |
+
|
| 298 |
+
@staticmethod
|
| 299 |
+
def _create_from(
|
| 300 |
+
model: nn.Module, disable_autograd_tracking: bool = False
|
| 301 |
+
) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]:
|
| 302 |
+
# TODO: We don't need to copy the model to create a stateless copy
|
| 303 |
+
model_copy = copy.deepcopy(model)
|
| 304 |
+
params, param_names, param_names_map = extract_weights(model_copy)
|
| 305 |
+
buffers, buffer_names, buffer_names_map = extract_buffers(model_copy)
|
| 306 |
+
if disable_autograd_tracking:
|
| 307 |
+
for param in params:
|
| 308 |
+
param.requires_grad_(False)
|
| 309 |
+
return (
|
| 310 |
+
FunctionalModuleWithBuffers(
|
| 311 |
+
model_copy, param_names, buffer_names, param_names_map, buffer_names_map
|
| 312 |
+
),
|
| 313 |
+
params,
|
| 314 |
+
buffers,
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
def forward(
|
| 318 |
+
self,
|
| 319 |
+
params: Iterable[Tensor],
|
| 320 |
+
buffers: Iterable[Tensor],
|
| 321 |
+
*args: Any,
|
| 322 |
+
**kwargs: Any,
|
| 323 |
+
) -> Any:
|
| 324 |
+
# Temporarily load the state back onto self.stateless_model
|
| 325 |
+
old_state = _swap_state(
|
| 326 |
+
self.stateless_model,
|
| 327 |
+
self.all_names_map,
|
| 328 |
+
tuple(params) + tuple(buffers),
|
| 329 |
+
)
|
| 330 |
+
try:
|
| 331 |
+
return self.stateless_model(*args, **kwargs)
|
| 332 |
+
finally:
|
| 333 |
+
# Remove the loaded state on self.stateless_model
|
| 334 |
+
_swap_state(self.stateless_model, self.all_names_map, old_state)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class FunctionalModule(nn.Module):
|
| 338 |
+
"""
|
| 339 |
+
This is the callable object returned by :func:`make_functional`.
|
| 340 |
+
"""
|
| 341 |
+
|
| 342 |
+
def __init__(
|
| 343 |
+
self,
|
| 344 |
+
stateless_model: nn.Module,
|
| 345 |
+
param_names: tuple[str, ...],
|
| 346 |
+
names_map: dict[str, list[str]],
|
| 347 |
+
) -> None:
|
| 348 |
+
super().__init__()
|
| 349 |
+
self.stateless_model = stateless_model
|
| 350 |
+
self.param_names = param_names
|
| 351 |
+
self.names_map = names_map
|
| 352 |
+
|
| 353 |
+
@staticmethod
|
| 354 |
+
def _create_from(
|
| 355 |
+
model: nn.Module, disable_autograd_tracking: bool = False
|
| 356 |
+
) -> tuple[FunctionalModule, tuple[Tensor, ...]]:
|
| 357 |
+
# TODO: We don't need to copy the model to create a stateless copy
|
| 358 |
+
model_copy = copy.deepcopy(model)
|
| 359 |
+
params, param_names, names_map = extract_weights(model_copy)
|
| 360 |
+
if disable_autograd_tracking:
|
| 361 |
+
for param in params:
|
| 362 |
+
param.requires_grad_(False)
|
| 363 |
+
return FunctionalModule(model_copy, param_names, names_map), params
|
| 364 |
+
|
| 365 |
+
def forward(self, params: Iterable[Tensor], *args: Any, **kwargs: Any) -> Any:
|
| 366 |
+
# Temporarily load the state back onto self.stateless_model
|
| 367 |
+
old_state = _swap_state(self.stateless_model, self.names_map, params)
|
| 368 |
+
try:
|
| 369 |
+
return self.stateless_model(*args, **kwargs)
|
| 370 |
+
finally:
|
| 371 |
+
# Remove the loaded state on self.stateless_model
|
| 372 |
+
_swap_state(self.stateless_model, self.names_map, old_state)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def make_functional(
|
| 376 |
+
model: nn.Module, disable_autograd_tracking: bool = False
|
| 377 |
+
) -> tuple[FunctionalModule, tuple[Tensor, ...]]:
|
| 378 |
+
"""make_functional(model, disable_autograd_tracking=False) -> func, params
|
| 379 |
+
|
| 380 |
+
Given a ``torch.nn.Module``, :func:`make_functional` extracts the state
|
| 381 |
+
(params) and returns a functional version of the model, ``func``. This
|
| 382 |
+
makes it so that it is possible use transforms over the parameters of
|
| 383 |
+
``model``.
|
| 384 |
+
|
| 385 |
+
``func`` can be invoked as follows:
|
| 386 |
+
|
| 387 |
+
.. code-block:: python
|
| 388 |
+
|
| 389 |
+
import torch
|
| 390 |
+
import torch.nn as nn
|
| 391 |
+
from functorch import make_functional
|
| 392 |
+
|
| 393 |
+
x = torch.randn(4, 3)
|
| 394 |
+
model = nn.Linear(3, 3)
|
| 395 |
+
func, params = make_functional(model)
|
| 396 |
+
func(params, x)
|
| 397 |
+
|
| 398 |
+
And here is an example of applying the grad transform over the parameters
|
| 399 |
+
of a model.
|
| 400 |
+
|
| 401 |
+
.. code-block:: python
|
| 402 |
+
|
| 403 |
+
import torch
|
| 404 |
+
import torch.nn as nn
|
| 405 |
+
from functorch import make_functional, grad
|
| 406 |
+
|
| 407 |
+
x = torch.randn(4, 3)
|
| 408 |
+
t = torch.randn(4, 3)
|
| 409 |
+
model = nn.Linear(3, 3)
|
| 410 |
+
func, params = make_functional(model)
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def compute_loss(params, x, t):
|
| 414 |
+
y = func(params, x)
|
| 415 |
+
return nn.functional.mse_loss(y, t)
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
grad_weights = grad(compute_loss)(params, x, t)
|
| 419 |
+
|
| 420 |
+
If the model has any buffers, please use :func:`make_functional_with_buffers` instead.
|
| 421 |
+
|
| 422 |
+
Args:
|
| 423 |
+
model (torch.nn.Module): Input model.
|
| 424 |
+
disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters.
|
| 425 |
+
The returned params are unrelated to the set of params from the original model. If False (default),
|
| 426 |
+
the params will have ``requires_grad=True`` on them (aka they will be trackable with regular
|
| 427 |
+
PyTorch autograd), matching the requires_grad-ness of the params from the original model.
|
| 428 |
+
Otherwise, the returned params will have ``requires_grad=False``. Default, False.
|
| 429 |
+
If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or
|
| 430 |
+
``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``.
|
| 431 |
+
Otherwise, if you're only planning on using functorch's gradient transforms,
|
| 432 |
+
then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking
|
| 433 |
+
history with PyTorch autograd.
|
| 434 |
+
|
| 435 |
+
"""
|
| 436 |
+
buffers = list(model.buffers())
|
| 437 |
+
if len(buffers) > 0:
|
| 438 |
+
raise RuntimeError(
|
| 439 |
+
"make_functional(model): `model` has buffers. Please use "
|
| 440 |
+
"make_functional_with_buffers(model) instead."
|
| 441 |
+
)
|
| 442 |
+
return FunctionalModule._create_from(
|
| 443 |
+
model, disable_autograd_tracking=disable_autograd_tracking
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def make_functional_with_buffers(
|
| 448 |
+
model: nn.Module, disable_autograd_tracking: bool = False
|
| 449 |
+
) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]:
|
| 450 |
+
"""make_functional_with_buffers(model, disable_autograd_tracking=False) -> func, params, buffers
|
| 451 |
+
|
| 452 |
+
Given a ``torch.nn.Module``, make_functional_with_buffers extracts the
|
| 453 |
+
state (params and buffers) and returns a functional version of the model
|
| 454 |
+
``func`` that can be invoked like a function.
|
| 455 |
+
|
| 456 |
+
``func`` can be invoked as follows:
|
| 457 |
+
|
| 458 |
+
.. code-block:: python
|
| 459 |
+
|
| 460 |
+
import torch
|
| 461 |
+
import torch.nn as nn
|
| 462 |
+
from functorch import make_functional_with_buffers
|
| 463 |
+
|
| 464 |
+
x = torch.randn(4, 3)
|
| 465 |
+
model = nn.Linear(3, 3)
|
| 466 |
+
func, params, buffers = make_functional_with_buffers(model)
|
| 467 |
+
func(params, buffers, x)
|
| 468 |
+
|
| 469 |
+
And here is an example of applying the grad transform over the parameters
|
| 470 |
+
of a model:
|
| 471 |
+
|
| 472 |
+
.. code-block:: python
|
| 473 |
+
|
| 474 |
+
import torch
|
| 475 |
+
import torch.nn as nn
|
| 476 |
+
from functorch import make_functional_with_buffers, grad
|
| 477 |
+
|
| 478 |
+
x = torch.randn(4, 3)
|
| 479 |
+
t = torch.randn(4, 3)
|
| 480 |
+
model = nn.Linear(3, 3)
|
| 481 |
+
func, params, buffers = make_functional_with_buffers(model)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def compute_loss(params, buffers, x, t):
|
| 485 |
+
y = func(params, buffers, x)
|
| 486 |
+
return nn.functional.mse_loss(y, t)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
grad_weights = grad(compute_loss)(params, buffers, x, t)
|
| 490 |
+
|
| 491 |
+
Args:
|
| 492 |
+
model (torch.nn.Module): Input model.
|
| 493 |
+
disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters.
|
| 494 |
+
The returned params are unrelated to the set of params from the original model. If False (default),
|
| 495 |
+
the params will have ``requires_grad=True`` on them (aka they will be trackable with regular
|
| 496 |
+
PyTorch autograd), matching the requires_grad-ness of the params from the original model.
|
| 497 |
+
Otherwise, the returned params will have ``requires_grad=False``. Default, False.
|
| 498 |
+
If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or
|
| 499 |
+
``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``.
|
| 500 |
+
Otherwise, if you're only planning on using functorch's gradient transforms,
|
| 501 |
+
then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking
|
| 502 |
+
history with PyTorch autograd.
|
| 503 |
+
|
| 504 |
+
"""
|
| 505 |
+
return FunctionalModuleWithBuffers._create_from(
|
| 506 |
+
model, disable_autograd_tracking=disable_autograd_tracking
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def transpose_stack(
|
| 511 |
+
tuple_of_tuple_of_tensors: tuple[tuple[Tensor, ...], ...],
|
| 512 |
+
) -> tuple[Tensor, ...]:
|
| 513 |
+
tuple_of_tuple_of_tensors = tuple(zip(*tuple_of_tuple_of_tensors))
|
| 514 |
+
results = tuple(
|
| 515 |
+
torch.stack(shards).detach() for shards in tuple_of_tuple_of_tensors
|
| 516 |
+
)
|
| 517 |
+
return results
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def combine_state_for_ensemble(
|
| 521 |
+
models: Sequence[nn.Module],
|
| 522 |
+
) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]:
|
| 523 |
+
"""combine_state_for_ensemble(models) -> func, params, buffers
|
| 524 |
+
|
| 525 |
+
Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`.
|
| 526 |
+
|
| 527 |
+
Given a list of ``M`` ``nn.Modules`` of the same class, stacks all of their
|
| 528 |
+
parameters and buffers together to make ``params`` and ``buffers``.
|
| 529 |
+
Each parameter and buffer in the result will have an additional dimension
|
| 530 |
+
of size ``M``.
|
| 531 |
+
|
| 532 |
+
:func:`combine_state_for_ensemble` also returns ``func``, a functional
|
| 533 |
+
version of one of the models in :attr:`models`. One cannot directly run
|
| 534 |
+
``func(params, buffers, *args, **kwargs)`` directly, you probably want to
|
| 535 |
+
use ``vmap(func, ...)(params, buffers, *args, **kwargs)``
|
| 536 |
+
|
| 537 |
+
Here's an example of how to ensemble over a very simple model:
|
| 538 |
+
|
| 539 |
+
.. code-block:: python
|
| 540 |
+
|
| 541 |
+
num_models = 5
|
| 542 |
+
batch_size = 64
|
| 543 |
+
in_features, out_features = 3, 3
|
| 544 |
+
models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)]
|
| 545 |
+
data = torch.randn(batch_size, 3)
|
| 546 |
+
|
| 547 |
+
fmodel, params, buffers = combine_state_for_ensemble(models)
|
| 548 |
+
output = vmap(fmodel, (0, 0, None))(params, buffers, data)
|
| 549 |
+
|
| 550 |
+
assert output.shape == (num_models, batch_size, out_features)
|
| 551 |
+
|
| 552 |
+
.. warning::
|
| 553 |
+
All of the modules being stacked together must be the same (except for
|
| 554 |
+
the values of their parameters/buffers). For example, they should be in the
|
| 555 |
+
same mode (training vs eval).
|
| 556 |
+
|
| 557 |
+
This API is subject to change -- we're investigating better ways to
|
| 558 |
+
create ensembles and would love your feedback how to improve this.
|
| 559 |
+
"""
|
| 560 |
+
if len(models) == 0:
|
| 561 |
+
raise RuntimeError(
|
| 562 |
+
"combine_state_for_ensemble: Expected at least one model, got 0."
|
| 563 |
+
)
|
| 564 |
+
if not (all(m.training for m in models) or all(not m.training for m in models)):
|
| 565 |
+
raise RuntimeError(
|
| 566 |
+
"combine_state_for_ensemble: Expected all models to "
|
| 567 |
+
"have the same training/eval mode."
|
| 568 |
+
)
|
| 569 |
+
model0_typ = type(models[0])
|
| 570 |
+
if not all(type(m) is model0_typ for m in models):
|
| 571 |
+
raise RuntimeError(
|
| 572 |
+
"combine_state_for_ensemble: Expected all models to be of the same class."
|
| 573 |
+
)
|
| 574 |
+
funcs, params, buffers = zip(
|
| 575 |
+
*[make_functional_with_buffers(model) for model in models]
|
| 576 |
+
)
|
| 577 |
+
params = transpose_stack(params)
|
| 578 |
+
buffers = transpose_stack(buffers)
|
| 579 |
+
return funcs[0], params, buffers
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def functional_init(
|
| 583 |
+
model_class: type[nn.Module],
|
| 584 |
+
ensemble_shape: tuple[()] | tuple[int, ...] = (),
|
| 585 |
+
device: torch.types.Device = "cpu",
|
| 586 |
+
) -> Callable[..., tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]]:
|
| 587 |
+
def wrapped(
|
| 588 |
+
*args: Any, **kwargs: Any
|
| 589 |
+
) -> tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]:
|
| 590 |
+
if len(ensemble_shape) >= 2:
|
| 591 |
+
raise ValueError("NYI: ensemble_shape with more than 1 element")
|
| 592 |
+
if len(ensemble_shape) == 0:
|
| 593 |
+
model = model_class(*args, **kwargs).to(device)
|
| 594 |
+
return make_functional_deprecated_v1(model)
|
| 595 |
+
num_models = ensemble_shape[0] # type: ignore[misc]
|
| 596 |
+
if num_models <= 0:
|
| 597 |
+
raise ValueError(f"num_models {num_models} should be > 0")
|
| 598 |
+
# NB: Not very efficient, more of a POC
|
| 599 |
+
models = tuple(
|
| 600 |
+
model_class(*args, **kwargs).to(device) for _ in range(num_models)
|
| 601 |
+
)
|
| 602 |
+
_, fn, names = make_functional_deprecated_v1(model_class(*args, **kwargs))
|
| 603 |
+
weights = tuple(make_functional_deprecated_v1(model)[0] for model in models)
|
| 604 |
+
weights = tuple(zip(*weights))
|
| 605 |
+
weights = tuple(torch.stack(shards).detach() for shards in weights)
|
| 606 |
+
return weights, fn, names
|
| 607 |
+
|
| 608 |
+
return wrapped
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def functional_init_with_buffers(
|
| 612 |
+
model_class: type[nn.Module],
|
| 613 |
+
ensemble_shape: tuple[()] | tuple[int, ...] = (),
|
| 614 |
+
device: torch.types.Device = "cpu",
|
| 615 |
+
) -> Callable[
|
| 616 |
+
...,
|
| 617 |
+
tuple[
|
| 618 |
+
tuple[Tensor, ...],
|
| 619 |
+
tuple[Tensor, ...],
|
| 620 |
+
Callable[..., Any],
|
| 621 |
+
tuple[str, ...],
|
| 622 |
+
tuple[str, ...],
|
| 623 |
+
]
|
| 624 |
+
| tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]],
|
| 625 |
+
]:
|
| 626 |
+
def wrapped(
|
| 627 |
+
*args: Any, **kwargs: Any
|
| 628 |
+
) -> (
|
| 629 |
+
tuple[
|
| 630 |
+
tuple[Tensor, ...],
|
| 631 |
+
tuple[Tensor, ...],
|
| 632 |
+
Callable[..., Any],
|
| 633 |
+
tuple[str, ...],
|
| 634 |
+
tuple[str, ...],
|
| 635 |
+
]
|
| 636 |
+
| tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]
|
| 637 |
+
):
|
| 638 |
+
if len(ensemble_shape) >= 2:
|
| 639 |
+
raise ValueError("NYI: ensemble_shape with more than 1 element")
|
| 640 |
+
if len(ensemble_shape) == 0:
|
| 641 |
+
model = model_class(*args, **kwargs).to(device)
|
| 642 |
+
return make_functional_deprecated_v1(model)
|
| 643 |
+
num_models = ensemble_shape[0] # type: ignore[misc]
|
| 644 |
+
if num_models <= 0:
|
| 645 |
+
raise ValueError(f"num_models {num_models} should be > 0")
|
| 646 |
+
# NB: Not very efficient, more of a POC
|
| 647 |
+
models = tuple(
|
| 648 |
+
model_class(*args, **kwargs).to(device) for _ in range(num_models)
|
| 649 |
+
)
|
| 650 |
+
(
|
| 651 |
+
_,
|
| 652 |
+
_,
|
| 653 |
+
fn,
|
| 654 |
+
weight_names,
|
| 655 |
+
buffer_names,
|
| 656 |
+
) = make_functional_with_buffers_deprecated_v1(model_class(*args, **kwargs))
|
| 657 |
+
weights, buffers = zip(
|
| 658 |
+
*tuple(
|
| 659 |
+
make_functional_with_buffers_deprecated_v1(model)[:2]
|
| 660 |
+
for model in models
|
| 661 |
+
)
|
| 662 |
+
)
|
| 663 |
+
weights = tuple(zip(*weights))
|
| 664 |
+
weights = tuple(torch.stack(shards).detach() for shards in weights)
|
| 665 |
+
buffers = tuple(zip(*buffers))
|
| 666 |
+
buffers = tuple(torch.stack(shards).detach() for shards in buffers)
|
| 667 |
+
return weights, buffers, fn, weight_names, buffer_names
|
| 668 |
+
|
| 669 |
+
return wrapped
|
venv/lib/python3.14/site-packages/torch/_functorch/partitioners.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
venv/lib/python3.14/site-packages/torch/_functorch/predispatch.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
This module contains pre-dispatch wrappers for functorch operations
|
| 9 |
+
that enable proper tracing in PT2 non-strict export/compile fx graph.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch._C._functorch import (
|
| 18 |
+
_add_batch_dim as _add_batch_dim_impl,
|
| 19 |
+
_remove_batch_dim as _remove_batch_dim_impl,
|
| 20 |
+
_vmap_decrement_nesting as _vmap_decrement_nesting_impl,
|
| 21 |
+
_vmap_increment_nesting as _vmap_increment_nesting_impl,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
import threading
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _add_batch_dim(self: torch.Tensor, batch_dim: int, level: int) -> torch.Tensor:
|
| 30 |
+
"""
|
| 31 |
+
Thin wrapper around torch._C._add_batch_dim that is used to proxy in
|
| 32 |
+
PT2 export/compile fx graph
|
| 33 |
+
"""
|
| 34 |
+
from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
|
| 35 |
+
|
| 36 |
+
mode = _maybe_find_pre_dispatch_tf_mode_for_export()
|
| 37 |
+
batch_dim = self.ndim + batch_dim if batch_dim < 0 else batch_dim
|
| 38 |
+
|
| 39 |
+
if mode:
|
| 40 |
+
return torch.overrides.handle_torch_function(
|
| 41 |
+
_add_batch_dim, (self,), self, batch_dim, level
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
res = _add_batch_dim_impl(self, batch_dim, level)
|
| 45 |
+
return res
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _remove_batch_dim(
|
| 49 |
+
self: torch.Tensor, level: int, batch_size: int, out_dim: int
|
| 50 |
+
) -> torch.Tensor:
|
| 51 |
+
"""
|
| 52 |
+
Thin wrapper around torch._C._remove_batch_dim that is used to proxy in
|
| 53 |
+
PT2 export/compile fx graph
|
| 54 |
+
"""
|
| 55 |
+
from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
|
| 56 |
+
|
| 57 |
+
mode = _maybe_find_pre_dispatch_tf_mode_for_export()
|
| 58 |
+
|
| 59 |
+
if mode:
|
| 60 |
+
return torch.overrides.handle_torch_function(
|
| 61 |
+
_remove_batch_dim, (self,), self, level, batch_size, out_dim
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
res = _remove_batch_dim_impl(self, level, batch_size, out_dim)
|
| 65 |
+
return res
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _vmap_increment_nesting(batch_size: int, randomness: str) -> int:
|
| 69 |
+
"""
|
| 70 |
+
Thin wrapper around torch._C._vmap_increment_nesting that is used
|
| 71 |
+
to proxy in export/compile graph
|
| 72 |
+
"""
|
| 73 |
+
from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
|
| 74 |
+
|
| 75 |
+
mode = _maybe_find_pre_dispatch_tf_mode_for_export()
|
| 76 |
+
|
| 77 |
+
if mode:
|
| 78 |
+
return torch.overrides.handle_torch_function(
|
| 79 |
+
_vmap_increment_nesting, (batch_size,), batch_size, randomness
|
| 80 |
+
)
|
| 81 |
+
res = _vmap_increment_nesting_impl(batch_size, randomness)
|
| 82 |
+
return res
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _vmap_decrement_nesting() -> int:
|
| 86 |
+
"""
|
| 87 |
+
Thin wrapper around torch._C._vmap_increment_nesting that is used
|
| 88 |
+
to proxy in export/compile graph
|
| 89 |
+
"""
|
| 90 |
+
from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
|
| 91 |
+
|
| 92 |
+
mode = _maybe_find_pre_dispatch_tf_mode_for_export()
|
| 93 |
+
|
| 94 |
+
if mode:
|
| 95 |
+
return torch.overrides.handle_torch_function(
|
| 96 |
+
_vmap_decrement_nesting,
|
| 97 |
+
(),
|
| 98 |
+
)
|
| 99 |
+
return _vmap_decrement_nesting_impl()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# Global variables for lazy_load_decompositions
|
| 103 |
+
DECOMPOSITIONS_LOADED: bool = False
|
| 104 |
+
DECOMPOSITIONS_LOCK: threading.Lock | None = None
|
| 105 |
+
VMAP_DECOMPOSITIONS_LIB: torch.library.Library | None = None
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def lazy_load_decompositions() -> None:
|
| 109 |
+
"""
|
| 110 |
+
Lazy loading of vmap decompositions with pre-dispatch support.
|
| 111 |
+
"""
|
| 112 |
+
from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
|
| 113 |
+
|
| 114 |
+
mode = _maybe_find_pre_dispatch_tf_mode_for_export()
|
| 115 |
+
|
| 116 |
+
if mode:
|
| 117 |
+
return torch.overrides.handle_torch_function(lazy_load_decompositions, ())
|
| 118 |
+
|
| 119 |
+
global DECOMPOSITIONS_LOADED, DECOMPOSITIONS_LOCK, VMAP_DECOMPOSITIONS_LIB
|
| 120 |
+
|
| 121 |
+
if DECOMPOSITIONS_LOADED:
|
| 122 |
+
return
|
| 123 |
+
|
| 124 |
+
# Initialize lock if needed
|
| 125 |
+
if DECOMPOSITIONS_LOCK is None:
|
| 126 |
+
import threading
|
| 127 |
+
|
| 128 |
+
DECOMPOSITIONS_LOCK = threading.Lock()
|
| 129 |
+
|
| 130 |
+
with DECOMPOSITIONS_LOCK:
|
| 131 |
+
if DECOMPOSITIONS_LOADED:
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
import os
|
| 135 |
+
|
| 136 |
+
if not (os.environ.get("PYTORCH_JIT", "1") == "1" and __debug__):
|
| 137 |
+
DECOMPOSITIONS_LOADED = True
|
| 138 |
+
return
|
| 139 |
+
|
| 140 |
+
# use an alternate way to register an operator into the decomposition table
|
| 141 |
+
# _register_jit_decomposition doesn't work for some operators, e.g. addr,
|
| 142 |
+
# because the Tensor types generated cannot be unioned by torchscript
|
| 143 |
+
# decomp should be type OpOverload
|
| 144 |
+
VMAP_DECOMPOSITIONS_LIB = torch.library.Library(
|
| 145 |
+
"aten", "IMPL", "FuncTorchBatched"
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
from torch._decomp import decomposition_table
|
| 149 |
+
|
| 150 |
+
def _register_python_decomposition_vmap(decomp: torch._ops.OpOverload) -> None:
|
| 151 |
+
if VMAP_DECOMPOSITIONS_LIB is None:
|
| 152 |
+
raise AssertionError("VMAP_DECOMPOSITIONS_LIB must not be None")
|
| 153 |
+
if decomp in decomposition_table:
|
| 154 |
+
VMAP_DECOMPOSITIONS_LIB.impl(decomp, decomposition_table[decomp])
|
| 155 |
+
else:
|
| 156 |
+
raise RuntimeError(f"could not find decomposition for {decomp}")
|
| 157 |
+
|
| 158 |
+
_register_python_decomposition_vmap(torch.ops.aten.mse_loss_backward.default)
|
| 159 |
+
_register_python_decomposition_vmap(
|
| 160 |
+
torch.ops.aten.smooth_l1_loss_backward.default
|
| 161 |
+
)
|
| 162 |
+
_register_python_decomposition_vmap(torch.ops.aten.huber_loss_backward.default)
|
| 163 |
+
_register_python_decomposition_vmap(torch.ops.aten.nll_loss_forward.default)
|
| 164 |
+
_register_python_decomposition_vmap(torch.ops.aten.nll_loss2d_forward.default)
|
| 165 |
+
_register_python_decomposition_vmap(torch.ops.aten.nll_loss_backward.default)
|
| 166 |
+
_register_python_decomposition_vmap(torch.ops.aten.nll_loss2d_backward.default)
|
| 167 |
+
_register_python_decomposition_vmap(torch.ops.aten.addr.default)
|
| 168 |
+
|
| 169 |
+
DECOMPOSITIONS_LOADED = True
|
venv/lib/python3.14/site-packages/torch/_functorch/pyfunctorch.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
from abc import ABC, abstractmethod
|
| 5 |
+
from functools import cached_property
|
| 6 |
+
from typing import Any, TYPE_CHECKING
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.utils._pytree as pytree
|
| 10 |
+
from torch._C._functorch import (
|
| 11 |
+
CFunctionalizeInterpreterPtr,
|
| 12 |
+
CGradInterpreterPtr,
|
| 13 |
+
CInterpreter,
|
| 14 |
+
CJvpInterpreterPtr,
|
| 15 |
+
CVmapInterpreterPtr,
|
| 16 |
+
pop_dynamic_layer_stack,
|
| 17 |
+
push_dynamic_layer_stack,
|
| 18 |
+
RandomnessType,
|
| 19 |
+
TransformType,
|
| 20 |
+
)
|
| 21 |
+
from torch.autograd.forward_ad import _set_fwd_grad_enabled
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from collections.abc import Generator
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
This file contains the functorch integration with PyDispatcher.
|
| 30 |
+
|
| 31 |
+
PyDispatcher does not understand functorch's DynamicLayerStack dispatching
|
| 32 |
+
logic because it is entirely implemented in C++ in the fallbacks for two
|
| 33 |
+
dispatch keys, FuncTorchDynamicLayer{Front, Back}Mode (PyDispatcher is unable
|
| 34 |
+
to directly reuse C++ boxed fallbacks).
|
| 35 |
+
|
| 36 |
+
Instead of trying to hammer PyDispatcher into understanding those fallbacks,
|
| 37 |
+
we re-implement the logic of peeking the top of the stack for an interpreter,
|
| 38 |
+
selecting the interpreter to dispatch on, etc, in Python. This leads to a
|
| 39 |
+
simpler design.
|
| 40 |
+
|
| 41 |
+
The main difference between C++ functorch and PyDispatcher's functorch logic
|
| 42 |
+
is that:
|
| 43 |
+
- C++ functorch needs to manually tweak dispatch keys to ping-pong between
|
| 44 |
+
DynamicLayerFrontMode and DynamicLayerBackMode.
|
| 45 |
+
- PyDispatcher's functorch logic pops an Interpreter from the top of the stack
|
| 46 |
+
and asks it to execute the rule associated with the Interpreter.
|
| 47 |
+
|
| 48 |
+
In C++ we do the ping-pong because e.g. vmap rules are associated with the
|
| 49 |
+
batched DispatchKey, but in PyDispatcher we are able to avoid this by asking
|
| 50 |
+
the user to register a batching rule directly to a transform that an
|
| 51 |
+
interpreter then invokes.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# FuncTorchInterpreter is the Python version of Interpreter (recall that
|
| 56 |
+
# the DynamicLayerStack is a stack of interpreters).
|
| 57 |
+
# It is a wrapper around the actual C++ Interpreter object.
|
| 58 |
+
#
|
| 59 |
+
# Keep the methods in sync with aten/src/ATen/functorch/Interpreter.h
|
| 60 |
+
class FuncTorchInterpreter(ABC):
|
| 61 |
+
def __init__(self, cptr: Any) -> None:
|
| 62 |
+
self._cptr = cptr
|
| 63 |
+
|
| 64 |
+
# Process an operation. eg for vmap, this is invoking a batching rule.
|
| 65 |
+
# Conceptually this is analogous to Interpreter::process in C++
|
| 66 |
+
@abstractmethod
|
| 67 |
+
def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
|
| 68 |
+
pass
|
| 69 |
+
|
| 70 |
+
# lower an operation from this Interpreter to the next Interpreter on the stack.
|
| 71 |
+
# Concretely, this involves temporarily popping the current Interpreter.
|
| 72 |
+
# Conceptually this is analogous to Interpreter::sendToNextInterpreter in C++
|
| 73 |
+
def lower(self) -> contextlib.AbstractContextManager[Any]:
|
| 74 |
+
return temporarily_pop_interpreter_stack()
|
| 75 |
+
|
| 76 |
+
def level(self) -> int:
|
| 77 |
+
return self._cptr.level()
|
| 78 |
+
|
| 79 |
+
def key(self) -> TransformType:
|
| 80 |
+
return self._cptr.key()
|
| 81 |
+
|
| 82 |
+
def get_state(self) -> tuple[Any, ...]:
|
| 83 |
+
raise NotImplementedError
|
| 84 |
+
|
| 85 |
+
def check_state(self, state: tuple[Any, ...]) -> bool:
|
| 86 |
+
return state == self.get_state()
|
| 87 |
+
|
| 88 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 89 |
+
state = self.__dict__.copy()
|
| 90 |
+
state.pop("_cptr", None)
|
| 91 |
+
return state
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@contextlib.contextmanager
|
| 95 |
+
def temporarily_pop_interpreter_stack() -> Generator[None, None, None]:
|
| 96 |
+
try:
|
| 97 |
+
saved = pop_dynamic_layer_stack()
|
| 98 |
+
yield
|
| 99 |
+
finally:
|
| 100 |
+
push_dynamic_layer_stack(saved)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@contextlib.contextmanager
|
| 104 |
+
def temporarily_clear_interpreter_stack() -> Generator[list[Any], None, None]:
|
| 105 |
+
stack: list[Any] = []
|
| 106 |
+
try:
|
| 107 |
+
while torch._C._functorch.peek_interpreter_stack() is not None:
|
| 108 |
+
stack.append(pop_dynamic_layer_stack())
|
| 109 |
+
yield list(stack)
|
| 110 |
+
finally:
|
| 111 |
+
while stack:
|
| 112 |
+
push_dynamic_layer_stack(stack.pop())
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@contextlib.contextmanager
|
| 116 |
+
def temporarily_restore_interpreter_stack(
|
| 117 |
+
stack: list[Any] | None,
|
| 118 |
+
) -> Generator[None, None, None]:
|
| 119 |
+
pushed: list[Any] = []
|
| 120 |
+
if stack is None:
|
| 121 |
+
return
|
| 122 |
+
try:
|
| 123 |
+
for s in reversed(stack):
|
| 124 |
+
push_dynamic_layer_stack(s)
|
| 125 |
+
pushed.append(s)
|
| 126 |
+
yield
|
| 127 |
+
finally:
|
| 128 |
+
for _ in reversed(pushed):
|
| 129 |
+
# TODO: would be nice to assert that the layers are the same, but
|
| 130 |
+
# Python object identity is not preserved
|
| 131 |
+
pop_dynamic_layer_stack()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class VmapInterpreter(FuncTorchInterpreter):
|
| 135 |
+
def __init__(self, cdata: CInterpreter) -> None:
|
| 136 |
+
if cdata.key() != TransformType.Vmap:
|
| 137 |
+
raise AssertionError(f"expected TransformType.Vmap, got {cdata.key()}")
|
| 138 |
+
# NOTE: [Interpreter cdata vs cptr]
|
| 139 |
+
# cdata is a generic CInterpreter. We wrap it in a CVmapInterpreterPtr
|
| 140 |
+
# so that we can access methods specific to the vmap interpreter
|
| 141 |
+
self._cdata = cdata
|
| 142 |
+
|
| 143 |
+
@cached_property
|
| 144 |
+
# pyrefly: ignore [bad-override]
|
| 145 |
+
def _cptr(self) -> CVmapInterpreterPtr:
|
| 146 |
+
return CVmapInterpreterPtr(self._cdata)
|
| 147 |
+
|
| 148 |
+
def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
|
| 149 |
+
kernel = op.functorch_table[TransformType.Vmap]
|
| 150 |
+
return kernel(self, *args, **kwargs)
|
| 151 |
+
|
| 152 |
+
def batch_size(self) -> int:
|
| 153 |
+
return self._cptr.batchSize()
|
| 154 |
+
|
| 155 |
+
def randomness(self) -> str:
|
| 156 |
+
typ = self._cptr.randomness()
|
| 157 |
+
if typ == RandomnessType.Error:
|
| 158 |
+
return "error"
|
| 159 |
+
elif typ == RandomnessType.Same:
|
| 160 |
+
return "same"
|
| 161 |
+
elif typ == RandomnessType.Different:
|
| 162 |
+
return "different"
|
| 163 |
+
raise RuntimeError(f"Unknown RandomnessType: {typ}")
|
| 164 |
+
|
| 165 |
+
def get_state(self) -> tuple[Any, ...]:
|
| 166 |
+
return (self.key().name, self.level(), self.randomness())
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@contextlib.contextmanager
|
| 170 |
+
def nested(
|
| 171 |
+
*contexts: contextlib.AbstractContextManager[Any],
|
| 172 |
+
) -> Generator[tuple[contextlib.AbstractContextManager[Any], ...], None, None]:
|
| 173 |
+
with contextlib.ExitStack() as stack:
|
| 174 |
+
for ctx in contexts:
|
| 175 |
+
stack.enter_context(ctx)
|
| 176 |
+
yield contexts
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class GradInterpreter(FuncTorchInterpreter):
|
| 180 |
+
def __init__(self, cdata: CInterpreter) -> None:
|
| 181 |
+
if cdata.key() != TransformType.Grad:
|
| 182 |
+
raise AssertionError(f"expected TransformType.Grad, got {cdata.key()}")
|
| 183 |
+
# See NOTE: [Interpreter cdata vs cptr]
|
| 184 |
+
self._cdata = cdata
|
| 185 |
+
|
| 186 |
+
@cached_property
|
| 187 |
+
# pyrefly: ignore [bad-override]
|
| 188 |
+
def _cptr(self) -> CGradInterpreterPtr:
|
| 189 |
+
return CGradInterpreterPtr(self._cdata)
|
| 190 |
+
|
| 191 |
+
def lift(
|
| 192 |
+
self, args: tuple[Any, ...], kwargs: dict[str, Any]
|
| 193 |
+
) -> tuple[tuple[Any, ...], dict[str, Any]]:
|
| 194 |
+
args, kwargs = pytree.tree_map_only(
|
| 195 |
+
torch.Tensor, self._cptr.lift, [args, kwargs]
|
| 196 |
+
)
|
| 197 |
+
return args, kwargs
|
| 198 |
+
|
| 199 |
+
def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
|
| 200 |
+
kernel = op.functorch_table[TransformType.Grad]
|
| 201 |
+
args, kwargs = self.lift(args, kwargs)
|
| 202 |
+
return kernel(self, *args, **kwargs)
|
| 203 |
+
|
| 204 |
+
# GradInterpreter has custom lower because of the no_grad interaction
|
| 205 |
+
# See NOTE [grad and vjp interaction with no_grad]
|
| 206 |
+
# This logic is mirrored from C++ GradInterpreterPtr::sendToNextInterpreter
|
| 207 |
+
def lower(self) -> contextlib.AbstractContextManager[Any]:
|
| 208 |
+
prev_grad_mode = self.prev_grad_mode()
|
| 209 |
+
if not prev_grad_mode:
|
| 210 |
+
return nested(torch.no_grad(), super().lower())
|
| 211 |
+
return super().lower()
|
| 212 |
+
|
| 213 |
+
def prev_grad_mode(self) -> bool:
|
| 214 |
+
return self._cptr.prevGradMode()
|
| 215 |
+
|
| 216 |
+
def get_state(self) -> tuple[Any, ...]:
|
| 217 |
+
return (self.key().name, self.level(), self.prev_grad_mode())
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class JvpInterpreter(FuncTorchInterpreter):
|
| 221 |
+
def __init__(self, cdata: CInterpreter) -> None:
|
| 222 |
+
if cdata.key() != TransformType.Jvp:
|
| 223 |
+
raise AssertionError(f"expected TransformType.Jvp, got {cdata.key()}")
|
| 224 |
+
# See NOTE: [Interpreter cdata vs cptr]
|
| 225 |
+
self._cdata = cdata
|
| 226 |
+
|
| 227 |
+
@cached_property
|
| 228 |
+
# pyrefly: ignore [bad-override]
|
| 229 |
+
def _cptr(self) -> CJvpInterpreterPtr:
|
| 230 |
+
return CJvpInterpreterPtr(self._cdata)
|
| 231 |
+
|
| 232 |
+
def lift(
|
| 233 |
+
self, args: tuple[Any, ...], kwargs: dict[str, Any]
|
| 234 |
+
) -> tuple[tuple[Any, ...], dict[str, Any]]:
|
| 235 |
+
args, kwargs = pytree.tree_map_only(
|
| 236 |
+
torch.Tensor, self._cptr.lift, [args, kwargs]
|
| 237 |
+
)
|
| 238 |
+
return args, kwargs
|
| 239 |
+
|
| 240 |
+
def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
|
| 241 |
+
kernel = op.functorch_table[TransformType.Jvp]
|
| 242 |
+
args, kwargs = self.lift(args, kwargs)
|
| 243 |
+
return kernel(self, *args, **kwargs)
|
| 244 |
+
|
| 245 |
+
# Jvp has custom lower because of the no_fwd_grad interaction
|
| 246 |
+
# See NOTE [grad and vjp interaction with no_grad] for related info.
|
| 247 |
+
# This logic is mirrored from C++ JvpInterpreterPtr::sendToNextInterpreter
|
| 248 |
+
def lower(self) -> contextlib.AbstractContextManager[Any]:
|
| 249 |
+
prev_fwd_grad_mode = self.prev_fwd_grad_mode()
|
| 250 |
+
if not prev_fwd_grad_mode:
|
| 251 |
+
return nested(_set_fwd_grad_enabled(False), super().lower())
|
| 252 |
+
return super().lower()
|
| 253 |
+
|
| 254 |
+
def prev_fwd_grad_mode(self) -> bool:
|
| 255 |
+
return self._cptr.prevFwdGradMode()
|
| 256 |
+
|
| 257 |
+
def get_state(self) -> tuple[Any, ...]:
|
| 258 |
+
return (self.key().name, self.level(), self.prev_fwd_grad_mode())
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class FunctionalizeInterpreter(FuncTorchInterpreter):
|
| 262 |
+
def __init__(self, cdata: CInterpreter) -> None:
|
| 263 |
+
if cdata.key() != TransformType.Functionalize:
|
| 264 |
+
raise AssertionError(
|
| 265 |
+
f"expected TransformType.Functionalize, got {cdata.key()}"
|
| 266 |
+
)
|
| 267 |
+
self._cdata = cdata
|
| 268 |
+
|
| 269 |
+
@cached_property
|
| 270 |
+
# pyrefly: ignore [bad-override]
|
| 271 |
+
def _cptr(self) -> CFunctionalizeInterpreterPtr:
|
| 272 |
+
return CFunctionalizeInterpreterPtr(self._cdata)
|
| 273 |
+
|
| 274 |
+
def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
|
| 275 |
+
kernel = op.functorch_table[TransformType.Functionalize]
|
| 276 |
+
return kernel(self, *args, **kwargs)
|
| 277 |
+
|
| 278 |
+
def functionalize_add_back_views(self) -> bool:
|
| 279 |
+
return self._cptr.functionalizeAddBackViews()
|
| 280 |
+
|
| 281 |
+
def get_state(self) -> tuple[Any, ...]:
|
| 282 |
+
return (self.key().name, self.level())
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def coerce_cinterpreter(cinterpreter: CInterpreter) -> FuncTorchInterpreter:
|
| 286 |
+
key = cinterpreter.key()
|
| 287 |
+
if key == TransformType.Grad:
|
| 288 |
+
return GradInterpreter(cinterpreter)
|
| 289 |
+
if key == TransformType.Vmap:
|
| 290 |
+
return VmapInterpreter(cinterpreter)
|
| 291 |
+
if key == TransformType.Jvp:
|
| 292 |
+
return JvpInterpreter(cinterpreter)
|
| 293 |
+
if key == TransformType.Functionalize:
|
| 294 |
+
return FunctionalizeInterpreter(cinterpreter)
|
| 295 |
+
raise RuntimeError(f"NYI: PyDispatcher has not implemented support for {key}")
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def retrieve_current_functorch_interpreter() -> FuncTorchInterpreter:
|
| 299 |
+
interpreter = torch._C._functorch.peek_interpreter_stack()
|
| 300 |
+
if interpreter is None:
|
| 301 |
+
raise AssertionError("interpreter must not be None")
|
| 302 |
+
return coerce_cinterpreter(interpreter)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def retrieve_all_functorch_interpreters() -> list[FuncTorchInterpreter]:
|
| 306 |
+
cis = torch._C._functorch.get_interpreter_stack()
|
| 307 |
+
if cis is None:
|
| 308 |
+
return []
|
| 309 |
+
return [coerce_cinterpreter(ci) for ci in cis]
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def compare_functorch_state(states: list[tuple[Any, ...]]) -> bool:
|
| 313 |
+
# There are four possible cases covered here:
|
| 314 |
+
# 1. Current stack empty AND stack when generated not empty -> Invalidate
|
| 315 |
+
# 2. Current stack not empty AND stack when generated empty -> Invalidate
|
| 316 |
+
# 3. Current stack and generated stack empty -> Valid FX graph
|
| 317 |
+
# 4. Current stack and generated stack not empty -> Valid if both states match
|
| 318 |
+
peek = torch._C._functorch.peek_interpreter_stack()
|
| 319 |
+
if (peek is None and len(states) != 0) or (peek is not None and len(states) == 0):
|
| 320 |
+
return False
|
| 321 |
+
|
| 322 |
+
cis = retrieve_all_functorch_interpreters()
|
| 323 |
+
return len(cis) == len(states) and all(
|
| 324 |
+
ci.check_state(state) for ci, state in zip(cis, states)
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def dispatch_functorch(op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
|
| 329 |
+
interpreter = retrieve_current_functorch_interpreter()
|
| 330 |
+
# In traditional PyTorch operators, DispatchKey::FuncTorchTensorWrapper's
|
| 331 |
+
# unwrap_dead_tensors fallback handles unwrapping dead tensor wrappers.
|
| 332 |
+
# PyDispatcher sidesteps the PyTorch dispatcher when dealing with functorch
|
| 333 |
+
# transforms, so we manually unwrap the dead tensors here.
|
| 334 |
+
# This logic won't need to exist when we have mode-only functorch.
|
| 335 |
+
args, kwargs = pytree.tree_map_only(
|
| 336 |
+
torch.Tensor, torch._C._functorch.unwrap_if_dead, (args, kwargs)
|
| 337 |
+
)
|
| 338 |
+
return interpreter.process(op, args, kwargs)
|
venv/lib/python3.14/site-packages/torch/_functorch/python_key.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
__all__ = ["make_fx", "dispatch_trace", "PythonKeyTracer", "pythonkey_decompose"]
|
| 7 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 8 |
+
decompose,
|
| 9 |
+
dispatch_trace,
|
| 10 |
+
make_fx,
|
| 11 |
+
PythonKeyTracer,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
pythonkey_decompose = decompose
|
venv/lib/python3.14/site-packages/torch/_functorch/pytree_hacks.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
# TODO: remove this file when the migration of the pytree utility is done
|
| 10 |
+
from torch.utils._pytree import tree_map_, treespec_pprint
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
__all__ = ["tree_map_", "treespec_pprint"]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
with warnings.catch_warnings():
|
| 17 |
+
warnings.simplefilter("always")
|
| 18 |
+
warnings.warn(
|
| 19 |
+
"`torch._functorch.pytree_hacks` is deprecated and will be removed in a future release. "
|
| 20 |
+
"Please `use torch.utils._pytree` instead.",
|
| 21 |
+
DeprecationWarning,
|
| 22 |
+
stacklevel=2,
|
| 23 |
+
)
|
venv/lib/python3.14/site-packages/torch/_functorch/top_operators_github_usage.py
ADDED
|
@@ -0,0 +1,631 @@
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
From https://docs.google.com/spreadsheets/d/12R3nCOLskxPYjjiNkdqy4OdQ65eQp_htebXGODsjSeA/edit#gid=0
|
| 6 |
+
Try to keep this list in sync with that.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import operator
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
top_torch: list[tuple[str, int]] = [
|
| 13 |
+
("t", 6837449),
|
| 14 |
+
("tensor", 585786),
|
| 15 |
+
("mode", 462182),
|
| 16 |
+
("cat", 394818),
|
| 17 |
+
("max", 368038),
|
| 18 |
+
("zeros", 329495),
|
| 19 |
+
("load", 327756),
|
| 20 |
+
("no_grad", 294694),
|
| 21 |
+
("save", 265130),
|
| 22 |
+
("from_numpy", 243063),
|
| 23 |
+
("manual_seed", 165044),
|
| 24 |
+
("ones", 153696),
|
| 25 |
+
("randn", 150796),
|
| 26 |
+
("stack", 133358),
|
| 27 |
+
("sum", 130772),
|
| 28 |
+
("arange", 98087),
|
| 29 |
+
("rand", 94715),
|
| 30 |
+
("mean", 88546),
|
| 31 |
+
("exp", 73883),
|
| 32 |
+
("zeros_like", 72831),
|
| 33 |
+
("min", 72248),
|
| 34 |
+
("sigmoid", 66798),
|
| 35 |
+
("log", 62135),
|
| 36 |
+
("matmul", 47811),
|
| 37 |
+
("clamp", 45304),
|
| 38 |
+
("sqrt", 44911),
|
| 39 |
+
("abs", 43535),
|
| 40 |
+
("tanh", 42793),
|
| 41 |
+
("empty", 40311),
|
| 42 |
+
("argmax", 38435),
|
| 43 |
+
("bmm", 33984),
|
| 44 |
+
("pow", 33571),
|
| 45 |
+
("norm", 31125),
|
| 46 |
+
("mm", 30995),
|
| 47 |
+
("is_tensor", 29546),
|
| 48 |
+
("ones_like", 29512),
|
| 49 |
+
("nonzero", 28681),
|
| 50 |
+
("full", 28373),
|
| 51 |
+
("unsqueeze", 27911),
|
| 52 |
+
("where", 26585),
|
| 53 |
+
("randperm", 26450),
|
| 54 |
+
("eye", 24342),
|
| 55 |
+
("mul", 23236),
|
| 56 |
+
("topk", 22537),
|
| 57 |
+
("as_tensor", 21967),
|
| 58 |
+
("sort", 21412),
|
| 59 |
+
("squeeze", 20863),
|
| 60 |
+
("randint", 20771),
|
| 61 |
+
("linspace", 20041),
|
| 62 |
+
("add", 19201),
|
| 63 |
+
("transpose", 18663),
|
| 64 |
+
("split", 18325),
|
| 65 |
+
("gather", 17904),
|
| 66 |
+
("set_grad_enabled", 16013),
|
| 67 |
+
("sin", 15669),
|
| 68 |
+
("cos", 15562),
|
| 69 |
+
("div", 15513),
|
| 70 |
+
("index_select", 14866),
|
| 71 |
+
("multinomial", 14331),
|
| 72 |
+
("flatten", 14267),
|
| 73 |
+
("isnan", 14170),
|
| 74 |
+
("randn_like", 13096),
|
| 75 |
+
("eq", 12680),
|
| 76 |
+
("einsum", 12480),
|
| 77 |
+
("round", 12367),
|
| 78 |
+
("floor", 11628),
|
| 79 |
+
("allclose", 11000),
|
| 80 |
+
("reshape", 10605),
|
| 81 |
+
("diag", 10167),
|
| 82 |
+
("chunk", 9581),
|
| 83 |
+
("std", 9379),
|
| 84 |
+
("set_default_tensor_type", 9281),
|
| 85 |
+
("triu", 8559),
|
| 86 |
+
("meshgrid", 8292),
|
| 87 |
+
("set_num_threads", 8126),
|
| 88 |
+
("unique", 7964),
|
| 89 |
+
("full_like", 7780),
|
| 90 |
+
("tril", 7538),
|
| 91 |
+
("dot", 7275),
|
| 92 |
+
("sign", 6943),
|
| 93 |
+
("equal", 6916),
|
| 94 |
+
("normal", 6750),
|
| 95 |
+
("cumsum", 6556),
|
| 96 |
+
("dist", 6058),
|
| 97 |
+
("isfinite", 6030),
|
| 98 |
+
("gt", 5935),
|
| 99 |
+
("set_printoptions", 5888),
|
| 100 |
+
("range", 5491),
|
| 101 |
+
("empty_like", 5351),
|
| 102 |
+
("flip", 5342),
|
| 103 |
+
("masked_select", 5341),
|
| 104 |
+
("bernoulli", 5262),
|
| 105 |
+
("atan", 5253),
|
| 106 |
+
("var", 5247),
|
| 107 |
+
("prod", 5200),
|
| 108 |
+
("erf", 5088),
|
| 109 |
+
("inverse", 5072),
|
| 110 |
+
("addmm", 4854),
|
| 111 |
+
("logsumexp", 4582),
|
| 112 |
+
("fft", 4436),
|
| 113 |
+
("lt", 4421),
|
| 114 |
+
("log2", 4316),
|
| 115 |
+
("enable_grad", 4238),
|
| 116 |
+
("rand_like", 4187),
|
| 117 |
+
("argsort", 3972),
|
| 118 |
+
("seed", 3932),
|
| 119 |
+
("mv", 3547),
|
| 120 |
+
("ger", 3309),
|
| 121 |
+
("ge", 3248),
|
| 122 |
+
("atan2", 3210),
|
| 123 |
+
("ceil", 3202),
|
| 124 |
+
("ne", 3075),
|
| 125 |
+
("bincount", 3063),
|
| 126 |
+
("acos", 3055),
|
| 127 |
+
("rsqrt", 3031),
|
| 128 |
+
("svd", 3029),
|
| 129 |
+
("numel", 3003),
|
| 130 |
+
("log1p", 2840),
|
| 131 |
+
("unbind", 2808),
|
| 132 |
+
("le", 2714),
|
| 133 |
+
("isinf", 2707),
|
| 134 |
+
("cross", 2646),
|
| 135 |
+
("set_default_dtype", 2536),
|
| 136 |
+
("argmin", 2535),
|
| 137 |
+
("sparse_coo_tensor", 2489),
|
| 138 |
+
("log10", 2304),
|
| 139 |
+
("kthvalue", 2192),
|
| 140 |
+
("set_rng_state", 2158),
|
| 141 |
+
("get_rng_state", 1996),
|
| 142 |
+
("get_default_dtype", 1879),
|
| 143 |
+
("det", 1868),
|
| 144 |
+
("qr", 1864),
|
| 145 |
+
("histc", 1852),
|
| 146 |
+
("symeig", 1832),
|
| 147 |
+
("trace", 1801),
|
| 148 |
+
("median", 1795),
|
| 149 |
+
("addcmul", 1751),
|
| 150 |
+
("remainder", 1717),
|
| 151 |
+
("baddbmm", 1693),
|
| 152 |
+
("lgamma", 1665),
|
| 153 |
+
("repeat_interleave", 1598),
|
| 154 |
+
("fmod", 1576),
|
| 155 |
+
("reciprocal", 1575),
|
| 156 |
+
("tan", 1560),
|
| 157 |
+
("initial_seed", 1532),
|
| 158 |
+
("take", 1529),
|
| 159 |
+
("stft", 1487),
|
| 160 |
+
("get_num_threads", 1477),
|
| 161 |
+
("real", 1459),
|
| 162 |
+
("cholesky", 1406),
|
| 163 |
+
("quantize_per_tensor", 1392),
|
| 164 |
+
("diag_embed", 1364),
|
| 165 |
+
("lerp", 1363),
|
| 166 |
+
("asin", 1345),
|
| 167 |
+
("eig", 1333),
|
| 168 |
+
("trunc", 1290),
|
| 169 |
+
("diagonal", 1287),
|
| 170 |
+
("cosh", 1279),
|
| 171 |
+
("rfft", 1269),
|
| 172 |
+
("cumprod", 1260),
|
| 173 |
+
("addr", 1211),
|
| 174 |
+
("roll", 1198),
|
| 175 |
+
("narrow", 1188),
|
| 176 |
+
("digamma", 1172),
|
| 177 |
+
("square", 1163),
|
| 178 |
+
("sinh", 1131),
|
| 179 |
+
("logspace", 1084),
|
| 180 |
+
("broadcast_tensors", 1070),
|
| 181 |
+
("irfft", 1013),
|
| 182 |
+
("frac", 997),
|
| 183 |
+
("hann_window", 994),
|
| 184 |
+
("solve", 989),
|
| 185 |
+
("logdet", 977),
|
| 186 |
+
("expm1", 968),
|
| 187 |
+
("cdist", 946),
|
| 188 |
+
("addmv", 903),
|
| 189 |
+
("randint_like", 888),
|
| 190 |
+
("tensordot", 888),
|
| 191 |
+
("ifft", 877),
|
| 192 |
+
("true_divide", 854),
|
| 193 |
+
("erfinv", 830),
|
| 194 |
+
("addcdiv", 819),
|
| 195 |
+
("addbmm", 813),
|
| 196 |
+
("renorm", 781),
|
| 197 |
+
("pinverse", 753),
|
| 198 |
+
("isclose", 740),
|
| 199 |
+
("erfc", 729),
|
| 200 |
+
("is_storage", 725),
|
| 201 |
+
("triangular_solve", 723),
|
| 202 |
+
("rot90", 709),
|
| 203 |
+
("logical_not", 686),
|
| 204 |
+
("geqrf", 681),
|
| 205 |
+
("slogdet", 677),
|
| 206 |
+
("lu", 665),
|
| 207 |
+
("hamming_window", 659),
|
| 208 |
+
("orgqr", 651),
|
| 209 |
+
("ormqr", 622),
|
| 210 |
+
("is_floating_point", 602),
|
| 211 |
+
("diagflat", 562),
|
| 212 |
+
("cholesky_solve", 559),
|
| 213 |
+
("tril_indices", 552),
|
| 214 |
+
("chain_matmul", 551),
|
| 215 |
+
("triu_indices", 548),
|
| 216 |
+
("angle", 522),
|
| 217 |
+
("poisson", 505),
|
| 218 |
+
("matrix_power", 485),
|
| 219 |
+
("unique_consecutive", 471),
|
| 220 |
+
("quantize_per_channel", 465),
|
| 221 |
+
("std_mean", 458),
|
| 222 |
+
("bartlett_window", 447),
|
| 223 |
+
("var_mean", 428),
|
| 224 |
+
("lstsq", 421),
|
| 225 |
+
("logical_and", 419),
|
| 226 |
+
("mvlgamma", 411),
|
| 227 |
+
("blackman_window", 400),
|
| 228 |
+
("bitwise_not", 395),
|
| 229 |
+
("cholesky_inverse", 388),
|
| 230 |
+
("as_strided", 384),
|
| 231 |
+
("floor_divide", 353),
|
| 232 |
+
("cartesian_prod", 321),
|
| 233 |
+
("lu_solve", 317),
|
| 234 |
+
("set_flush_denormal", 310),
|
| 235 |
+
("empty_strided", 283),
|
| 236 |
+
("logical_xor", 282),
|
| 237 |
+
("polygamma", 282),
|
| 238 |
+
("logical_or", 280),
|
| 239 |
+
("set_num_interop_threads", 278),
|
| 240 |
+
("combinations", 274),
|
| 241 |
+
("trapz", 270),
|
| 242 |
+
("matrix_rank", 260),
|
| 243 |
+
("lu_unpack", 255),
|
| 244 |
+
("result_type", 244),
|
| 245 |
+
("conj", 231),
|
| 246 |
+
("cummax", 230),
|
| 247 |
+
("lobpcg", 229),
|
| 248 |
+
("bitwise_xor", 217),
|
| 249 |
+
("promote_types", 213),
|
| 250 |
+
("get_num_interop_threads", 211),
|
| 251 |
+
("cummin", 205),
|
| 252 |
+
("bitwise_and", 198),
|
| 253 |
+
("dequantize", 192),
|
| 254 |
+
("bitwise_or", 191),
|
| 255 |
+
("imag", 191),
|
| 256 |
+
("can_cast", 184),
|
| 257 |
+
("istft", 180),
|
| 258 |
+
("compiled_with_cxx11_abi", 159),
|
| 259 |
+
("is_complex", 151),
|
| 260 |
+
("block_diag", 136),
|
| 261 |
+
("pca_lowrank", 124),
|
| 262 |
+
("absolute", 122),
|
| 263 |
+
("svd_lowrank", 108),
|
| 264 |
+
("neg", 2),
|
| 265 |
+
]
|
| 266 |
+
|
| 267 |
+
top_nn_functional: list[tuple[str, int]] = [
|
| 268 |
+
("nn.functional.softmax", 10522),
|
| 269 |
+
("nn.functional.relu", 8572),
|
| 270 |
+
("nn.functional.interpolate", 7277),
|
| 271 |
+
("nn.functional.pad", 5207),
|
| 272 |
+
("nn.functional.log_softmax", 4699),
|
| 273 |
+
("nn.functional.normalize", 2338),
|
| 274 |
+
("nn.functional.cross_entropy", 2083),
|
| 275 |
+
("nn.functional.grid_sample", 1970),
|
| 276 |
+
("nn.functional.one_hot", 1967),
|
| 277 |
+
("nn.functional.mse_loss", 1920),
|
| 278 |
+
("nn.functional.conv2d", 1593),
|
| 279 |
+
("nn.functional.dropout", 1516),
|
| 280 |
+
("nn.functional.softplus", 1385),
|
| 281 |
+
("nn.functional.sigmoid", 1128),
|
| 282 |
+
("nn.functional.linear", 1036),
|
| 283 |
+
("nn.functional.gelu", 930),
|
| 284 |
+
("nn.functional.avg_pool2d", 899),
|
| 285 |
+
("nn.functional.max_pool2d", 876),
|
| 286 |
+
("nn.functional.nll_loss", 863),
|
| 287 |
+
("nn.functional.embedding", 737),
|
| 288 |
+
("nn.functional.tanh", 664),
|
| 289 |
+
("nn.functional.leaky_relu", 640),
|
| 290 |
+
("nn.functional.adaptive_avg_pool2d", 633),
|
| 291 |
+
("nn.functional.cosine_similarity", 627),
|
| 292 |
+
("nn.functional.unfold", 609),
|
| 293 |
+
("nn.functional.conv1d", 596),
|
| 294 |
+
("nn.functional.binary_cross_entropy_with_logits", 591),
|
| 295 |
+
("nn.functional.l1_loss", 571),
|
| 296 |
+
("nn.functional.binary_cross_entropy", 492),
|
| 297 |
+
("nn.functional.elu", 416),
|
| 298 |
+
("nn.functional.batch_norm", 413),
|
| 299 |
+
("nn.functional.upsample", 413),
|
| 300 |
+
("nn.functional.fold", 305),
|
| 301 |
+
("nn.functional.affine_grid", 298),
|
| 302 |
+
("nn.functional.max_pool1d", 297),
|
| 303 |
+
("nn.functional.torch", 294),
|
| 304 |
+
("nn.functional.threshold", 263),
|
| 305 |
+
("nn.functional.smooth_l1_loss", 262),
|
| 306 |
+
("nn.functional.pairwise_distance", 253),
|
| 307 |
+
("nn.functional.logsigmoid", 243),
|
| 308 |
+
("nn.functional.adaptive_max_pool2d", 235),
|
| 309 |
+
("nn.functional.relu6", 213),
|
| 310 |
+
("nn.functional.pixel_shuffle", 209),
|
| 311 |
+
("nn.functional.avg_pool3d", 203),
|
| 312 |
+
("nn.functional.bilinear", 203),
|
| 313 |
+
("nn.functional.conv_transpose2d", 201),
|
| 314 |
+
("nn.functional.gumbel_softmax", 197),
|
| 315 |
+
("nn.functional.max_unpool2d", 196),
|
| 316 |
+
("nn.functional.kl_div", 191),
|
| 317 |
+
("nn.functional.hardtanh", 189),
|
| 318 |
+
("nn.functional.ctc_loss", 185),
|
| 319 |
+
("nn.functional.layer_norm", 178),
|
| 320 |
+
("nn.functional.conv3d", 172),
|
| 321 |
+
("nn.functional.max_unpool3d", 167),
|
| 322 |
+
("nn.functional.hardshrink", 165),
|
| 323 |
+
("nn.functional.hardswish", 156),
|
| 324 |
+
("nn.functional.selu", 156),
|
| 325 |
+
("nn.functional.glu", 155),
|
| 326 |
+
("nn.functional.assert_int_or_pair", 150),
|
| 327 |
+
("nn.functional.hardsigmoid", 146),
|
| 328 |
+
("nn.functional.upsample_bilinear", 146),
|
| 329 |
+
("nn.functional.max_pool3d", 140),
|
| 330 |
+
("nn.functional.adaptive_avg_pool3d", 139),
|
| 331 |
+
("nn.functional.instance_norm", 124),
|
| 332 |
+
("nn.functional.embedding_bag", 122),
|
| 333 |
+
("nn.functional.upsample_nearest", 110),
|
| 334 |
+
("nn.functional.avg_pool1d", 105),
|
| 335 |
+
("nn.functional.prelu", 102),
|
| 336 |
+
("nn.functional.celu", 92),
|
| 337 |
+
("nn.functional.dropout2d", 86),
|
| 338 |
+
("nn.functional.hinge_embedding_loss", 82),
|
| 339 |
+
("nn.functional.softsign", 81),
|
| 340 |
+
("nn.functional.max_unpool1d", 74),
|
| 341 |
+
("nn.functional.silu", 74),
|
| 342 |
+
("nn.functional.softshrink", 70),
|
| 343 |
+
("nn.functional.leaky_relu_", 68),
|
| 344 |
+
("nn.functional.softmin", 67),
|
| 345 |
+
("nn.functional.channel_shuffle", 66),
|
| 346 |
+
("nn.functional.multilabel_margin_loss", 66),
|
| 347 |
+
("nn.functional.dropout3d", 65),
|
| 348 |
+
("nn.functional.multi_margin_loss", 65),
|
| 349 |
+
("nn.functional.lp_pool2d", 64),
|
| 350 |
+
("nn.functional.conv_transpose1d", 62),
|
| 351 |
+
("nn.functional.triplet_margin_loss", 62),
|
| 352 |
+
("nn.functional.tanhshrink", 61),
|
| 353 |
+
("nn.functional.adaptive_max_pool1d", 59),
|
| 354 |
+
("nn.functional.cosine_embedding_loss", 58),
|
| 355 |
+
("nn.functional.multi_head_attention_forward", 58),
|
| 356 |
+
("nn.functional.max_pool1d_with_indices", 53),
|
| 357 |
+
("nn.functional.poisson_nll_loss", 53),
|
| 358 |
+
("nn.functional.margin_ranking_loss", 52),
|
| 359 |
+
("nn.functional.soft_margin_loss", 52),
|
| 360 |
+
("nn.functional.adaptive_max_pool3d", 51),
|
| 361 |
+
("nn.functional.group_norm", 51),
|
| 362 |
+
("nn.functional.local_response_norm", 51),
|
| 363 |
+
("nn.functional.multilabel_soft_margin_loss", 51),
|
| 364 |
+
("nn.functional.relu_", 50),
|
| 365 |
+
("nn.functional.alpha_dropout", 49),
|
| 366 |
+
("nn.functional.feature_alpha_dropout", 49),
|
| 367 |
+
("nn.functional.lp_pool1d", 49),
|
| 368 |
+
("nn.functional.adaptive_max_pool1d_with_indices", 48),
|
| 369 |
+
("nn.functional.adaptive_max_pool2d_with_indices", 48),
|
| 370 |
+
("nn.functional.adaptive_max_pool3d_with_indices", 48),
|
| 371 |
+
("nn.functional.fractional_max_pool2d", 48),
|
| 372 |
+
("nn.functional.fractional_max_pool2d_with_indices", 48),
|
| 373 |
+
("nn.functional.fractional_max_pool3d", 48),
|
| 374 |
+
("nn.functional.fractional_max_pool3d_with_indices", 48),
|
| 375 |
+
("nn.functional.max_pool2d_with_indices", 48),
|
| 376 |
+
("nn.functional.max_pool3d_with_indices", 48),
|
| 377 |
+
("nn.functional.handle_torch_function", 47),
|
| 378 |
+
("nn.functional.has_torch_function", 47),
|
| 379 |
+
("nn.functional.adaptive_avg_pool1d", 43),
|
| 380 |
+
("nn.functional.pdist", 43),
|
| 381 |
+
("nn.functional.rrelu_", 37),
|
| 382 |
+
("nn.functional.elu_", 34),
|
| 383 |
+
("nn.functional.boolean_dispatch", 33),
|
| 384 |
+
("nn.functional.hardtanh_", 26),
|
| 385 |
+
("nn.functional.triplet_margin_with_distance_loss", 23),
|
| 386 |
+
("nn.functional.selu_", 20),
|
| 387 |
+
("nn.functional.pixel_unshuffle", 19),
|
| 388 |
+
("nn.functional.conv_transpose3d", 18),
|
| 389 |
+
("nn.functional.gaussian_nll_loss", 15),
|
| 390 |
+
("nn.functional.has_torch_function_unary", 15),
|
| 391 |
+
("nn.functional.has_torch_function_variadic", 15),
|
| 392 |
+
("nn.functional.celu_", 13),
|
| 393 |
+
("nn.functional.huber_loss", 7),
|
| 394 |
+
("nn.functional.mish", 4),
|
| 395 |
+
("nn.functional.threshold_", 3),
|
| 396 |
+
("nn.functional.grad", 2),
|
| 397 |
+
("nn.functional.conv_tbc", 1),
|
| 398 |
+
("nn.functional.math", 1),
|
| 399 |
+
]
|
| 400 |
+
|
| 401 |
+
top_nn_module: list[tuple[str, int, str | None]] = [
|
| 402 |
+
("nn.Module", 927129, None),
|
| 403 |
+
("nn.Linear", 530688, "nn.functional.linear"),
|
| 404 |
+
("nn.Sequential", 384968, None),
|
| 405 |
+
("nn.Conv2d", 383320, "nn.functional.conv2d"),
|
| 406 |
+
("nn.ReLU", 318877, "nn.functional.relu"),
|
| 407 |
+
("nn.BatchNorm2d", 233265, "nn.functional.batch_norm"),
|
| 408 |
+
("nn.Dropout", 179268, "nn.functional.dropout"),
|
| 409 |
+
("nn.ModuleList", 171225, None),
|
| 410 |
+
("nn.Parameter", 153291, None),
|
| 411 |
+
("nn.CrossEntropyLoss", 152696, "nn.functional.cross_entropy"),
|
| 412 |
+
("nn.MaxPool2d", 138619, "nn.functional.max_pool2d"),
|
| 413 |
+
("nn.Embedding", 111844, "nn.functional.embedding"),
|
| 414 |
+
("nn.DataParallel", 104238, None),
|
| 415 |
+
("nn.MSELoss", 82954, "nn.functional.mse_loss"),
|
| 416 |
+
("nn.Sigmoid", 75810, "nn.functional.sigmoid"),
|
| 417 |
+
("nn.LeakyReLU", 65632, "nn.functional.leaky_relu"),
|
| 418 |
+
("nn.BatchNorm1d", 65374, "nn.functional.batch_norm"),
|
| 419 |
+
("nn.Softmax", 65114, "nn.functional.softmax"),
|
| 420 |
+
("nn.Tanh", 59445, "nn.functional.tanh"),
|
| 421 |
+
("nn.AdaptiveAvgPool2d", 59071, "nn.functional.adaptive_avg_pool2d"),
|
| 422 |
+
("nn.AvgPool2d", 58377, "nn.functional.avg_pool2d"),
|
| 423 |
+
("nn.ConvTranspose2d", 57524, "nn.functional.conv_transpose2d"),
|
| 424 |
+
("nn.LSTM", 57411, None),
|
| 425 |
+
("nn.Conv1d", 41108, "nn.functional.conv1d"),
|
| 426 |
+
("nn.LayerNorm", 36089, "nn.functional.layer_norm"),
|
| 427 |
+
("nn.BCELoss", 34005, "nn.functional.binary_cross_entropy"),
|
| 428 |
+
("nn.Upsample", 32527, "nn.functional.interpolate"),
|
| 429 |
+
("nn.BCEWithLogitsLoss", 29944, "nn.functional.binary_cross_entropy_with_logits"),
|
| 430 |
+
("nn.GRU", 25421, None),
|
| 431 |
+
("nn.Dropout2d", 23512, "nn.functional.dropout2d"),
|
| 432 |
+
("nn.LogSoftmax", 22897, "nn.functional.log_softmax"),
|
| 433 |
+
("nn.L1Loss", 22778, "nn.functional.l1_loss"),
|
| 434 |
+
("nn.GroupNorm", 22183, "nn.functional.group_norm"),
|
| 435 |
+
("nn.NLLLoss", 21751, "nn.functional.nll_loss"),
|
| 436 |
+
("nn.Conv3d", 20874, "nn.functional.conv3d"),
|
| 437 |
+
("nn.Identity", 17911, None),
|
| 438 |
+
("nn.InstanceNorm2d", 16426, "nn.functional.instance_norm"),
|
| 439 |
+
("nn.BatchNorm3d", 16378, "nn.functional.batch_norm"),
|
| 440 |
+
("nn.PReLU", 13472, "nn.functional.prelu"),
|
| 441 |
+
("nn.ReLU6", 12622, "nn.functional.relu6"),
|
| 442 |
+
("nn.ELU", 12508, "nn.functional.elu"),
|
| 443 |
+
("nn.LSTMCell", 10885, None),
|
| 444 |
+
("nn.Flatten", 10384, "torch.flatten"),
|
| 445 |
+
("nn.ModuleDict", 10255, None),
|
| 446 |
+
("nn.ReflectionPad2d", 9954, "nn.functional.pad"),
|
| 447 |
+
("nn.MaxPool3d", 9526, "nn.functional.max_pool3d"),
|
| 448 |
+
("nn.MaxPool1d", 9154, "nn.functional.max_pool1d"),
|
| 449 |
+
("nn.RNN", 9154, None),
|
| 450 |
+
("nn.ZeroPad2d", 8847, "nn.functional.pad"),
|
| 451 |
+
("nn.ParameterList", 7702, None),
|
| 452 |
+
("nn.SyncBatchNorm", 6814, None),
|
| 453 |
+
("nn.PixelShuffle", 6571, "nn.functional.pixel_shuffle"),
|
| 454 |
+
("nn.SmoothL1Loss", 6517, "nn.functional.smooth_l1_loss"),
|
| 455 |
+
("nn.Hardswish", 6458, "nn.functional.hardswish"),
|
| 456 |
+
("nn.AdaptiveMaxPool2d", 6071, "nn.functional.adaptive_max_pool2d"),
|
| 457 |
+
("nn.SELU", 6043, "nn.functional.selu"),
|
| 458 |
+
("nn.ConvTranspose3d", 6039, "nn.functional.conv_transpose3d"),
|
| 459 |
+
("nn.GRUCell", 5840, None),
|
| 460 |
+
("nn.ReplicationPad2d", 5600, "nn.functional.pad"),
|
| 461 |
+
("nn.KLDivLoss", 5541, "nn.functional.kl_div"),
|
| 462 |
+
("nn.ConvTranspose1d", 5183, "nn.functional.conv_transpose1d"),
|
| 463 |
+
("nn.Softplus", 5120, "nn.functional.softplus"),
|
| 464 |
+
("nn.SiLU", 4895, "nn.functional.silu"),
|
| 465 |
+
("nn.AvgPool3d", 4523, "nn.functional.avg_pool3d"),
|
| 466 |
+
("nn.CosineSimilarity", 4058, "nn.functional.cosine_similarity"),
|
| 467 |
+
("nn.GELU", 3932, "nn.functional.gelu"),
|
| 468 |
+
("nn.UpsamplingBilinear2d", 3673, "nn.functional.interpolate"),
|
| 469 |
+
("nn.InstanceNorm1d", 3658, "nn.functional.instance_norm"),
|
| 470 |
+
("nn.Transformer", 3604, None),
|
| 471 |
+
("nn.MultiheadAttention", 3435, "nn.functional.multi_head_attention_forward"),
|
| 472 |
+
("nn.AvgPool1d", 3195, "nn.functional.avg_pool1d"),
|
| 473 |
+
("nn.Dropout3d", 2964, "nn.functional.dropout3d"),
|
| 474 |
+
("nn.AdaptiveAvgPool3d", 2915, "nn.functional.adaptive_avg_pool3d"),
|
| 475 |
+
("nn.InstanceNorm3d", 2893, "nn.functional.instance_norm"),
|
| 476 |
+
("nn.Hardtanh", 2613, "nn.functional.hardtanh"),
|
| 477 |
+
("nn.MarginRankingLoss", 2568, "nn.functional.margin_ranking_loss"),
|
| 478 |
+
("nn.GLU", 2526, "nn.functional.glu"),
|
| 479 |
+
("nn.AdaptiveAvgPool1d", 2481, "nn.functional.adaptive_avg_pool1d"),
|
| 480 |
+
("nn.EmbeddingBag", 2344, "nn.functional.embedding_bag"),
|
| 481 |
+
("nn.TransformerEncoderLayer", 2292, None),
|
| 482 |
+
("nn.TransformerEncoder", 2091, None),
|
| 483 |
+
("nn.MaxUnpool2d", 2031, "nn.functional.max_unpool2d"),
|
| 484 |
+
("nn.UpsamplingNearest2d", 2004, "nn.functional.interpolate"),
|
| 485 |
+
("nn.ConstantPad1d", 1904, "nn.functional.pad"),
|
| 486 |
+
("nn.ConstantPad2d", 1791, "nn.functional.pad"),
|
| 487 |
+
("nn.CTCLoss", 1789, "nn.functional.ctc_loss"),
|
| 488 |
+
("nn.AdaptiveMaxPool1d", 1713, "nn.functional.adaptive_max_pool1d"),
|
| 489 |
+
("nn.AdaptiveLogSoftmaxWithLoss", 1665, None),
|
| 490 |
+
("nn.Bilinear", 1664, "nn.functional.bilinear"),
|
| 491 |
+
("nn.RNNCell", 1653, None),
|
| 492 |
+
("nn.MultiLabelSoftMarginLoss", 1624, "nn.functional.multilabel_soft_margin_loss"),
|
| 493 |
+
("nn.Unfold", 1452, "nn.functional.unfold"),
|
| 494 |
+
("nn.RReLU", 1431, "nn.functional.rrelu"),
|
| 495 |
+
("nn.CosineEmbeddingLoss", 1357, "nn.functional.cosine_embedding_loss"),
|
| 496 |
+
("nn.LocalResponseNorm", 1331, "nn.functional.local_response_norm"),
|
| 497 |
+
("nn.Softmax2d", 1300, "nn.functional.softmax"),
|
| 498 |
+
("nn.PairwiseDistance", 1241, "nn.functional.pairwise_distance"),
|
| 499 |
+
("nn.LogSigmoid", 1235, "nn.functional.logsigmoid"),
|
| 500 |
+
("nn.TripletMarginLoss", 1230, "nn.functional.triplet_margin_loss"),
|
| 501 |
+
("nn.RNNBase", 1133, None),
|
| 502 |
+
("nn.Threshold", 1043, "nn.functional.threshold"),
|
| 503 |
+
("nn.AdaptiveMaxPool3d", 1025, "nn.functional.adaptive_max_pool3d"),
|
| 504 |
+
("nn.CELU", 1018, "nn.functional.celu"),
|
| 505 |
+
("nn.NLLLoss2d", 966, "nn.functional.nll_loss"),
|
| 506 |
+
("nn.Softsign", 877, "nn.functional.softsign"),
|
| 507 |
+
("nn.ReplicationPad1d", 862, "nn.functional.pad"),
|
| 508 |
+
("nn.SoftMarginLoss", 856, "nn.functional.soft_margin_loss"),
|
| 509 |
+
("nn.ParameterDict", 742, None),
|
| 510 |
+
("nn.ReflectionPad1d", 731, "nn.functional.pad"),
|
| 511 |
+
("nn.Softshrink", 713, "nn.functional.softshrink"),
|
| 512 |
+
("nn.AlphaDropout", 710, "nn.functional.alpha_dropout"),
|
| 513 |
+
("nn.Tanhshrink", 681, "nn.functional.tanhshrink"),
|
| 514 |
+
("nn.PoissonNLLLoss", 676, "nn.functional.poisson_nll_loss"),
|
| 515 |
+
("nn.MaxUnpool3d", 660, "nn.functional.max_unpool3d"),
|
| 516 |
+
("nn.Fold", 630, "nn.functional.fold"),
|
| 517 |
+
("nn.MultiMarginLoss", 622, "nn.functional.multi_margin_loss"),
|
| 518 |
+
("nn.TransformerDecoderLayer", 614, None),
|
| 519 |
+
("nn.TransformerDecoder", 607, None),
|
| 520 |
+
("nn.Hardshrink", 592, "nn.functional.hardshrink"),
|
| 521 |
+
("nn.ConstantPad3d", 582, "nn.functional.pad"),
|
| 522 |
+
("nn.MultiLabelMarginLoss", 580, "nn.functional.multilabel_margin_loss"),
|
| 523 |
+
("nn.LPPool2d", 550, "nn.functional.lp_pool2d"),
|
| 524 |
+
("nn.Softmin", 537, "nn.functional.softmin"),
|
| 525 |
+
("nn.MaxUnpool1d", 518, "nn.functional.max_unpool1d"),
|
| 526 |
+
("nn.FractionalMaxPool2d", 484, "nn.functional.fractional_max_pool2d"),
|
| 527 |
+
("nn.Hardsigmoid", 477, "nn.functional.hardsigmoid"),
|
| 528 |
+
("nn.ReplicationPad3d", 470, "nn.functional.pad"),
|
| 529 |
+
("nn.HingeEmbeddingLoss", 442, "nn.functional.hinge_embedding_loss"),
|
| 530 |
+
("nn.LPPool1d", 386, "nn.functional.lp_pool1d"),
|
| 531 |
+
("nn.FractionalMaxPool3d", 252, "nn.functional.fractional_max_pool3d"),
|
| 532 |
+
("nn.Container", 217, None),
|
| 533 |
+
("nn.Unflatten", 206, "nn.functional.unflatten"),
|
| 534 |
+
("nn.FeatureAlphaDropout", 136, "nn.functional.feature_alpha_dropout"),
|
| 535 |
+
(
|
| 536 |
+
"nn.TripletMarginWithDistanceLoss",
|
| 537 |
+
107,
|
| 538 |
+
"nn.functional.triplet_margin_with_distance_loss",
|
| 539 |
+
),
|
| 540 |
+
("nn.ChannelShuffle", 90, "nn.functional.channel_shuffle"),
|
| 541 |
+
("nn.RNNCellBase", 88, None),
|
| 542 |
+
("nn.LazyLinear", 81, "nn.functional.linear"),
|
| 543 |
+
("nn.UninitializedParameter", 60, None),
|
| 544 |
+
("nn.CrossMapLRN2d", 59, None),
|
| 545 |
+
("nn.GaussianNLLLoss", 55, "nn.functional.gaussian_nll_loss"),
|
| 546 |
+
("nn.PixelUnshuffle", 45, "nn.functional.pixel_unshuffle"),
|
| 547 |
+
("nn.Mish", 31, "nn.functional.mish"),
|
| 548 |
+
("nn.ReflectionPad3d", 22, "nn.functional.pad"),
|
| 549 |
+
("nn.HuberLoss", 18, "nn.functional.huber_loss"),
|
| 550 |
+
("nn.LazyConv2d", 15, None),
|
| 551 |
+
("nn.LazyConv1d", 9, None),
|
| 552 |
+
("nn.LazyConv3d", 8, None),
|
| 553 |
+
("nn.LazyConvTranspose1d", 8, None),
|
| 554 |
+
("nn.LazyConvTranspose2d", 8, None),
|
| 555 |
+
("nn.LazyConvTranspose3d", 8, None),
|
| 556 |
+
("nn.LazyBatchNorm1d", 3, None),
|
| 557 |
+
("nn.LazyBatchNorm2d", 3, None),
|
| 558 |
+
("nn.LazyBatchNorm3d", 3, None),
|
| 559 |
+
("nn.UninitializedBuffer", 3, None),
|
| 560 |
+
]
|
| 561 |
+
|
| 562 |
+
# No rankings because these are a little hard to get rankings for
|
| 563 |
+
method_only_ops: list[str] = [
|
| 564 |
+
"bfloat16",
|
| 565 |
+
"bool",
|
| 566 |
+
"byte",
|
| 567 |
+
"char",
|
| 568 |
+
"contiguous",
|
| 569 |
+
"cpu",
|
| 570 |
+
"cuda",
|
| 571 |
+
"detach",
|
| 572 |
+
"double",
|
| 573 |
+
"expand",
|
| 574 |
+
"expand_as",
|
| 575 |
+
"float",
|
| 576 |
+
"get_device",
|
| 577 |
+
"half",
|
| 578 |
+
"hardshrink",
|
| 579 |
+
"index_add",
|
| 580 |
+
"index_copy",
|
| 581 |
+
"index_fill",
|
| 582 |
+
"index_put",
|
| 583 |
+
"int",
|
| 584 |
+
"is_contiguous",
|
| 585 |
+
"is_pinned",
|
| 586 |
+
"is_set_to",
|
| 587 |
+
"is_shared",
|
| 588 |
+
"is_signed",
|
| 589 |
+
"item",
|
| 590 |
+
"long",
|
| 591 |
+
"masked_scatter",
|
| 592 |
+
"masked_fill",
|
| 593 |
+
"narrow_copy",
|
| 594 |
+
"numpy",
|
| 595 |
+
"pin_memory",
|
| 596 |
+
"repeat",
|
| 597 |
+
"reshape_as",
|
| 598 |
+
"select",
|
| 599 |
+
"short",
|
| 600 |
+
"storage_offset",
|
| 601 |
+
"sum_to_size",
|
| 602 |
+
"to",
|
| 603 |
+
"to_mkldnn",
|
| 604 |
+
"tolist",
|
| 605 |
+
"type",
|
| 606 |
+
"type_as",
|
| 607 |
+
"unfold",
|
| 608 |
+
"view",
|
| 609 |
+
"view_as",
|
| 610 |
+
]
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def get_nn_functional_top_list() -> list[tuple[str, int]]:
|
| 614 |
+
top_nn_functional_: dict[str, int] = dict(top_nn_functional)
|
| 615 |
+
for _, count, functional_name in top_nn_module:
|
| 616 |
+
if functional_name is None:
|
| 617 |
+
continue
|
| 618 |
+
if functional_name == "torch.flatten":
|
| 619 |
+
continue
|
| 620 |
+
if functional_name not in top_nn_functional_:
|
| 621 |
+
top_nn_functional_[functional_name] = count
|
| 622 |
+
else:
|
| 623 |
+
top_nn_functional_[functional_name] += count
|
| 624 |
+
|
| 625 |
+
top_nn_functional_list = list(top_nn_functional_.items())
|
| 626 |
+
top_nn_functional_list.sort(key=operator.itemgetter(1), reverse=True)
|
| 627 |
+
return top_nn_functional_list
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
usage_count: dict[str, int] = dict(get_nn_functional_top_list())
|
| 631 |
+
usage_count.update(top_torch)
|
venv/lib/python3.14/site-packages/torch/_functorch/utils.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextlib
|
| 2 |
+
from collections.abc import Generator
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch._C._functorch import (
|
| 7 |
+
get_single_level_autograd_function_allowed,
|
| 8 |
+
set_single_level_autograd_function_allowed,
|
| 9 |
+
unwrap_if_dead,
|
| 10 |
+
)
|
| 11 |
+
from torch.utils._exposed_in import exposed_in
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"exposed_in",
|
| 16 |
+
"argnums_t",
|
| 17 |
+
"enable_single_level_autograd_function",
|
| 18 |
+
"unwrap_dead_wrappers",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@contextlib.contextmanager
|
| 23 |
+
def enable_single_level_autograd_function() -> Generator[None, None, None]:
|
| 24 |
+
try:
|
| 25 |
+
prev_state = get_single_level_autograd_function_allowed()
|
| 26 |
+
set_single_level_autograd_function_allowed(True)
|
| 27 |
+
yield
|
| 28 |
+
finally:
|
| 29 |
+
set_single_level_autograd_function_allowed(prev_state)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def unwrap_dead_wrappers(args: tuple[Any, ...]) -> tuple[Any, ...]:
|
| 33 |
+
# NB: doesn't use tree_map_only for performance reasons
|
| 34 |
+
result = tuple(
|
| 35 |
+
unwrap_if_dead(arg) if isinstance(arg, torch.Tensor) else arg for arg in args
|
| 36 |
+
)
|
| 37 |
+
return result
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
argnums_t = int | tuple[int, ...]
|
venv/lib/python3.14/site-packages/torch/_functorch/vmap.py
ADDED
|
@@ -0,0 +1,567 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import contextlib
|
| 10 |
+
import functools
|
| 11 |
+
import itertools
|
| 12 |
+
from collections.abc import Callable # noqa: TC003
|
| 13 |
+
from functools import partial
|
| 14 |
+
from typing import Any, cast, NoReturn, TYPE_CHECKING
|
| 15 |
+
from typing_extensions import ParamSpec, TypeVar
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
from torch._C._functorch import is_batchedtensor
|
| 20 |
+
from torch._functorch.predispatch import (
|
| 21 |
+
_add_batch_dim,
|
| 22 |
+
_remove_batch_dim,
|
| 23 |
+
_vmap_decrement_nesting,
|
| 24 |
+
_vmap_increment_nesting,
|
| 25 |
+
lazy_load_decompositions,
|
| 26 |
+
)
|
| 27 |
+
from torch.utils._pytree import (
|
| 28 |
+
_broadcast_to_and_flatten,
|
| 29 |
+
tree_flatten,
|
| 30 |
+
tree_map_,
|
| 31 |
+
tree_unflatten,
|
| 32 |
+
TreeSpec,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if TYPE_CHECKING:
|
| 37 |
+
from collections.abc import Generator, Iterable
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
_P = ParamSpec("_P")
|
| 41 |
+
_R = TypeVar("_R")
|
| 42 |
+
|
| 43 |
+
in_dims_t = int | tuple[Any, ...]
|
| 44 |
+
out_dims_t = int | tuple[int, ...] | None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def doesnt_support_saved_tensors_hooks(f: Callable[_P, _R]) -> Callable[_P, _R]:
|
| 48 |
+
message = (
|
| 49 |
+
"torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. "
|
| 50 |
+
"Please open an issue with your use case."
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
@functools.wraps(f)
|
| 54 |
+
def fn(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
| 55 |
+
with torch.autograd.graph.disable_saved_tensors_hooks(message):
|
| 56 |
+
return f(*args, **kwargs)
|
| 57 |
+
|
| 58 |
+
return fn
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Checks that all args-to-be-batched have the same batch dim size
|
| 62 |
+
def _validate_and_get_batch_size(
|
| 63 |
+
flat_in_dims: list[int | None], flat_args: list[Any]
|
| 64 |
+
) -> int:
|
| 65 |
+
batch_sizes = [
|
| 66 |
+
arg.size(in_dim)
|
| 67 |
+
for in_dim, arg in zip(flat_in_dims, flat_args)
|
| 68 |
+
if in_dim is not None
|
| 69 |
+
]
|
| 70 |
+
if len(batch_sizes) == 0:
|
| 71 |
+
raise ValueError("vmap: Expected at least one Tensor to vmap over")
|
| 72 |
+
if batch_sizes and any(size != batch_sizes[0] for size in batch_sizes):
|
| 73 |
+
raise ValueError(
|
| 74 |
+
f"vmap: Expected all tensors to have the same size in the mapped "
|
| 75 |
+
f"dimension, got sizes {batch_sizes} for the mapped dimension"
|
| 76 |
+
)
|
| 77 |
+
return batch_sizes[0]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _num_outputs(batched_outputs: Tensor | tuple[Tensor, ...]) -> int:
|
| 81 |
+
if isinstance(batched_outputs, tuple):
|
| 82 |
+
return len(batched_outputs)
|
| 83 |
+
return 1
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# If value is a tuple, check it has length `num_elements`.
|
| 87 |
+
# If value is not a tuple, make a tuple with `value` repeated `num_elements` times
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _as_tuple(
|
| 91 |
+
value: tuple[_R, ...] | _R,
|
| 92 |
+
num_elements: int,
|
| 93 |
+
error_message_lambda: Callable[[], str],
|
| 94 |
+
) -> tuple[_R, ...]:
|
| 95 |
+
if not isinstance(value, tuple):
|
| 96 |
+
return (value,) * num_elements
|
| 97 |
+
if len(value) != num_elements:
|
| 98 |
+
raise ValueError(error_message_lambda())
|
| 99 |
+
return value
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _process_batched_inputs(
|
| 103 |
+
in_dims: in_dims_t, args: tuple[Any, ...], func: Callable[..., Any]
|
| 104 |
+
) -> tuple[int, list[int | None], list[Any], TreeSpec]:
|
| 105 |
+
if not isinstance(in_dims, int) and not isinstance(in_dims, tuple):
|
| 106 |
+
raise ValueError(
|
| 107 |
+
f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
|
| 108 |
+
f"expected `in_dims` to be int or a (potentially nested) tuple "
|
| 109 |
+
f"matching the structure of inputs, got: {type(in_dims)}."
|
| 110 |
+
)
|
| 111 |
+
if len(args) == 0:
|
| 112 |
+
raise ValueError(
|
| 113 |
+
f"vmap({_get_name(func)})(<inputs>): got no inputs. Maybe you forgot to add "
|
| 114 |
+
f"inputs, or you are trying to vmap over a function with no inputs. "
|
| 115 |
+
f"The latter is unsupported."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
flat_args, args_spec = tree_flatten(args)
|
| 119 |
+
flat_in_dims = _broadcast_to_and_flatten(in_dims, args_spec)
|
| 120 |
+
if flat_in_dims is None:
|
| 121 |
+
raise ValueError(
|
| 122 |
+
f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
|
| 123 |
+
f"in_dims is not compatible with the structure of `inputs`. "
|
| 124 |
+
f"in_dims has structure {tree_flatten(in_dims)[1]} but inputs "
|
| 125 |
+
f"has structure {args_spec}."
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
for i, (arg, in_dim) in enumerate(zip(flat_args, flat_in_dims)):
|
| 129 |
+
if not isinstance(in_dim, int) and in_dim is not None:
|
| 130 |
+
raise ValueError(
|
| 131 |
+
f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
|
| 132 |
+
f"Got in_dim={in_dim} for an input but in_dim must be either "
|
| 133 |
+
f"an integer dimension or None."
|
| 134 |
+
)
|
| 135 |
+
if isinstance(in_dim, int) and not isinstance(arg, Tensor):
|
| 136 |
+
raise ValueError(
|
| 137 |
+
f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
|
| 138 |
+
f"Got in_dim={in_dim} for an input but the input is of type "
|
| 139 |
+
f"{type(arg)}. We cannot vmap over non-Tensor arguments, "
|
| 140 |
+
f"please use None as the respective in_dim"
|
| 141 |
+
)
|
| 142 |
+
if in_dim is not None and (in_dim < -arg.dim() or in_dim >= arg.dim()):
|
| 143 |
+
raise ValueError(
|
| 144 |
+
f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
|
| 145 |
+
f"Got in_dim={in_dim} for some input, but that input is a Tensor "
|
| 146 |
+
f"of dimensionality {arg.dim()} so expected in_dim to satisfy "
|
| 147 |
+
f"-{arg.dim()} <= in_dim < {arg.dim()}."
|
| 148 |
+
)
|
| 149 |
+
if in_dim is not None and in_dim < 0:
|
| 150 |
+
flat_in_dims[i] = in_dim % arg.dim()
|
| 151 |
+
|
| 152 |
+
return (
|
| 153 |
+
_validate_and_get_batch_size(flat_in_dims, flat_args),
|
| 154 |
+
flat_in_dims,
|
| 155 |
+
flat_args,
|
| 156 |
+
args_spec,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# Creates BatchedTensors for every Tensor in arg that should be batched.
|
| 161 |
+
# Returns the (potentially) batched arguments and the batch_size.
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# TODO: See if we can explain how flat works to the type checker
|
| 165 |
+
def _create_batched_inputs(
|
| 166 |
+
flat_in_dims: list[int | None],
|
| 167 |
+
flat_args: list[Any],
|
| 168 |
+
vmap_level: int,
|
| 169 |
+
args_spec: TreeSpec,
|
| 170 |
+
) -> tuple[Any, ...]:
|
| 171 |
+
# See NOTE [Ignored _remove_batch_dim, _add_batch_dim]
|
| 172 |
+
batched_inputs = [
|
| 173 |
+
arg if in_dim is None else _add_batch_dim(arg, in_dim, vmap_level)
|
| 174 |
+
for in_dim, arg in zip(flat_in_dims, flat_args)
|
| 175 |
+
]
|
| 176 |
+
return tree_unflatten(batched_inputs, args_spec)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _maybe_remove_batch_dim(
|
| 180 |
+
name: str,
|
| 181 |
+
batched_output: Any,
|
| 182 |
+
vmap_level: int,
|
| 183 |
+
batch_size: int,
|
| 184 |
+
out_dim: int | None,
|
| 185 |
+
) -> torch.Tensor:
|
| 186 |
+
if out_dim is None:
|
| 187 |
+
if isinstance(batched_output, torch.Tensor) and is_batchedtensor(
|
| 188 |
+
batched_output
|
| 189 |
+
):
|
| 190 |
+
raise ValueError(
|
| 191 |
+
f"vmap({name}, ...): `{name}` can not return a "
|
| 192 |
+
f"BatchedTensor when out_dim is None"
|
| 193 |
+
)
|
| 194 |
+
return batched_output
|
| 195 |
+
|
| 196 |
+
# out_dim is non None
|
| 197 |
+
if not isinstance(batched_output, torch.Tensor):
|
| 198 |
+
raise ValueError(
|
| 199 |
+
f"vmap({name}, ...): `{name}` must only return "
|
| 200 |
+
f"Tensors, got type {type(batched_output)}. "
|
| 201 |
+
"Did you mean to set out_dims= to None for output?"
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
return _remove_batch_dim(batched_output, vmap_level, batch_size, out_dim)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# Undos the batching (and any batch dimensions) associated with the `vmap_level`.
|
| 208 |
+
def _unwrap_batched(
|
| 209 |
+
batched_outputs: Tensor | tuple[Tensor, ...],
|
| 210 |
+
out_dims: out_dims_t,
|
| 211 |
+
vmap_level: int,
|
| 212 |
+
batch_size: int,
|
| 213 |
+
func: Callable[..., Any],
|
| 214 |
+
) -> tuple[Any, ...]:
|
| 215 |
+
flat_batched_outputs, output_spec = tree_flatten(batched_outputs)
|
| 216 |
+
|
| 217 |
+
def incompatible_error() -> NoReturn:
|
| 218 |
+
raise ValueError(
|
| 219 |
+
f"vmap({_get_name(func)}, ..., out_dims={out_dims})(<inputs>): "
|
| 220 |
+
f"out_dims is not compatible with the structure of `outputs`. "
|
| 221 |
+
f"out_dims has structure {tree_flatten(out_dims)[1]} but outputs "
|
| 222 |
+
f"has structure {output_spec}."
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
flat_out_dims: list[int | None] = []
|
| 226 |
+
if isinstance(batched_outputs, torch.Tensor):
|
| 227 |
+
# Some weird edge case requires us to spell out the following
|
| 228 |
+
# see test_out_dims_edge_case
|
| 229 |
+
if isinstance(out_dims, int):
|
| 230 |
+
flat_out_dims = [out_dims]
|
| 231 |
+
elif isinstance(out_dims, tuple) and len(out_dims) == 1:
|
| 232 |
+
flat_out_dims = list(out_dims)
|
| 233 |
+
elif out_dims is None:
|
| 234 |
+
flat_out_dims = [out_dims]
|
| 235 |
+
else:
|
| 236 |
+
incompatible_error()
|
| 237 |
+
else:
|
| 238 |
+
broadcast_result = _broadcast_to_and_flatten(out_dims, output_spec)
|
| 239 |
+
if broadcast_result is None:
|
| 240 |
+
incompatible_error()
|
| 241 |
+
else:
|
| 242 |
+
flat_out_dims = broadcast_result
|
| 243 |
+
|
| 244 |
+
flat_outputs = [
|
| 245 |
+
_maybe_remove_batch_dim(
|
| 246 |
+
_get_name(func), batched_output, vmap_level, batch_size, out_dim
|
| 247 |
+
)
|
| 248 |
+
for batched_output, out_dim in zip(flat_batched_outputs, flat_out_dims)
|
| 249 |
+
]
|
| 250 |
+
return tree_unflatten(flat_outputs, output_spec)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _check_int_or_none(x: Any, func: Callable[..., Any], out_dims: out_dims_t) -> None:
|
| 254 |
+
if isinstance(x, int):
|
| 255 |
+
return
|
| 256 |
+
if x is None:
|
| 257 |
+
return
|
| 258 |
+
raise ValueError(
|
| 259 |
+
f"vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must be "
|
| 260 |
+
f"an int, None or a python collection of ints representing where in the outputs the "
|
| 261 |
+
f"vmapped dimension should appear."
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _check_out_dims_is_int_or_int_pytree(
|
| 266 |
+
out_dims: out_dims_t, func: Callable[..., Any]
|
| 267 |
+
) -> None:
|
| 268 |
+
if isinstance(out_dims, int):
|
| 269 |
+
return
|
| 270 |
+
tree_map_(partial(_check_int_or_none, func=func, out_dims=out_dims), out_dims)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _get_name(func: Callable[..., Any]) -> str:
|
| 274 |
+
if hasattr(func, "__name__"):
|
| 275 |
+
return func.__name__
|
| 276 |
+
|
| 277 |
+
if isinstance(func, functools.partial):
|
| 278 |
+
return f"functools.partial({_get_name(func.func)}, ...)"
|
| 279 |
+
|
| 280 |
+
# Not all callables have __name__, in fact, only static functions/methods
|
| 281 |
+
# do. A callable created via nn.Module, to name one example, doesn't have a
|
| 282 |
+
# __name__.
|
| 283 |
+
return repr(func)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def vmap_impl(
|
| 287 |
+
func: Callable[_P, Tensor | tuple[Tensor, ...]],
|
| 288 |
+
in_dims: in_dims_t,
|
| 289 |
+
out_dims: out_dims_t,
|
| 290 |
+
randomness: str,
|
| 291 |
+
chunk_size: int | None,
|
| 292 |
+
*args: _P.args,
|
| 293 |
+
**kwargs: _P.kwargs,
|
| 294 |
+
) -> Any:
|
| 295 |
+
lazy_load_decompositions()
|
| 296 |
+
_check_out_dims_is_int_or_int_pytree(out_dims, func)
|
| 297 |
+
batch_size, flat_in_dims, flat_args, args_spec = _process_batched_inputs(
|
| 298 |
+
in_dims, args, func
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
if chunk_size is not None:
|
| 302 |
+
chunks_flat_args = _get_chunked_inputs(
|
| 303 |
+
flat_args, flat_in_dims, batch_size, chunk_size
|
| 304 |
+
)
|
| 305 |
+
return _chunked_vmap(
|
| 306 |
+
func,
|
| 307 |
+
flat_in_dims,
|
| 308 |
+
chunks_flat_args,
|
| 309 |
+
args_spec,
|
| 310 |
+
out_dims,
|
| 311 |
+
randomness,
|
| 312 |
+
**kwargs,
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
# If chunk_size is not specified.
|
| 316 |
+
return _flat_vmap(
|
| 317 |
+
func,
|
| 318 |
+
batch_size,
|
| 319 |
+
flat_in_dims,
|
| 320 |
+
flat_args,
|
| 321 |
+
args_spec,
|
| 322 |
+
out_dims,
|
| 323 |
+
randomness,
|
| 324 |
+
**kwargs,
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def get_chunk_sizes(total_elems: int, chunk_size: int) -> list[int]:
|
| 329 |
+
n_chunks = total_elems // chunk_size
|
| 330 |
+
chunk_sizes = [chunk_size] * n_chunks
|
| 331 |
+
# remainder chunk
|
| 332 |
+
remainder = total_elems % chunk_size
|
| 333 |
+
if remainder != 0:
|
| 334 |
+
chunk_sizes.append(remainder)
|
| 335 |
+
return chunk_sizes
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _get_chunked_inputs(
|
| 339 |
+
flat_args: list[Any],
|
| 340 |
+
flat_in_dims: list[int | None],
|
| 341 |
+
batch_size: int,
|
| 342 |
+
chunk_size: int | None,
|
| 343 |
+
) -> Iterable[tuple[Any, ...]]:
|
| 344 |
+
split_idxs = (batch_size,)
|
| 345 |
+
if chunk_size is not None:
|
| 346 |
+
chunk_sizes = get_chunk_sizes(batch_size, chunk_size)
|
| 347 |
+
split_idxs = tuple(itertools.accumulate(chunk_sizes))
|
| 348 |
+
|
| 349 |
+
flat_args_chunks = tuple(
|
| 350 |
+
(
|
| 351 |
+
t.tensor_split(split_idxs, dim=in_dim)
|
| 352 |
+
if in_dim is not None
|
| 353 |
+
else [
|
| 354 |
+
t,
|
| 355 |
+
]
|
| 356 |
+
* len(split_idxs)
|
| 357 |
+
)
|
| 358 |
+
for t, in_dim in zip(flat_args, flat_in_dims)
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
# transpose chunk dim and flatten structure
|
| 362 |
+
# chunks_flat_args is a list of flatten args
|
| 363 |
+
chunks_flat_args = zip(*flat_args_chunks)
|
| 364 |
+
return chunks_flat_args
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _flatten_chunks_output(
|
| 368 |
+
chunks_output_: list[Any],
|
| 369 |
+
) -> tuple[list[tuple[Any, ...]], TreeSpec]:
|
| 370 |
+
# chunks_output is a list of chunked outputs
|
| 371 |
+
# flatten chunked outputs:
|
| 372 |
+
flat_chunks_output: list[list[Any]] = []
|
| 373 |
+
arg_spec: TreeSpec | None = None
|
| 374 |
+
for output in chunks_output_:
|
| 375 |
+
flat_output, arg_specs = tree_flatten(output)
|
| 376 |
+
flat_chunks_output.append(flat_output)
|
| 377 |
+
if arg_spec is None:
|
| 378 |
+
arg_spec = arg_specs
|
| 379 |
+
|
| 380 |
+
# transpose chunk dim and flatten structure
|
| 381 |
+
# flat_output_chunks is flat list of chunks
|
| 382 |
+
flat_output_chunks = list(zip(*flat_chunks_output))
|
| 383 |
+
if arg_spec is None:
|
| 384 |
+
raise AssertionError("arg_spec must not be None")
|
| 385 |
+
return flat_output_chunks, arg_spec
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def _concat_chunked_outputs(
|
| 389 |
+
out_dims: out_dims_t,
|
| 390 |
+
arg_spec: TreeSpec,
|
| 391 |
+
flat_output_chunks: list[tuple[Any, ...] | None],
|
| 392 |
+
) -> list[Tensor]:
|
| 393 |
+
# concat chunks on out_dim
|
| 394 |
+
flat_out_dims = _broadcast_to_and_flatten(out_dims, arg_spec)
|
| 395 |
+
if flat_out_dims is None:
|
| 396 |
+
raise AssertionError("flat_out_dims must not be None")
|
| 397 |
+
if len(flat_out_dims) != len(flat_output_chunks):
|
| 398 |
+
raise AssertionError(
|
| 399 |
+
f"len(flat_out_dims)={len(flat_out_dims)} != len(flat_output_chunks)={len(flat_output_chunks)}"
|
| 400 |
+
)
|
| 401 |
+
flat_output: list[Tensor] = []
|
| 402 |
+
for idx, out_dim in enumerate(flat_out_dims):
|
| 403 |
+
chunk = flat_output_chunks[idx]
|
| 404 |
+
if chunk is None:
|
| 405 |
+
raise AssertionError(f"chunk at index {idx} must not be None")
|
| 406 |
+
flat_output.append(torch.cat(chunk, dim=out_dim))
|
| 407 |
+
# release tensors
|
| 408 |
+
flat_output_chunks[idx] = None
|
| 409 |
+
|
| 410 |
+
return flat_output
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
# Applies vmap on chunked_input and returns concatenated output over the chunks.
|
| 414 |
+
def _chunked_vmap(
|
| 415 |
+
func: Callable[_P, Tensor | tuple[Tensor, ...]],
|
| 416 |
+
flat_in_dims: list[int | None],
|
| 417 |
+
chunks_flat_args: Iterable[tuple[Any, ...]],
|
| 418 |
+
args_spec: TreeSpec,
|
| 419 |
+
out_dims: out_dims_t,
|
| 420 |
+
randomness: str,
|
| 421 |
+
**kwargs: Any,
|
| 422 |
+
) -> Any:
|
| 423 |
+
chunks_output: list[Any] = []
|
| 424 |
+
rs = torch.get_rng_state() if randomness == "same" else None
|
| 425 |
+
for flat_args_tuple in chunks_flat_args:
|
| 426 |
+
flat_args = list(flat_args_tuple)
|
| 427 |
+
batch_size = _validate_and_get_batch_size(flat_in_dims, flat_args)
|
| 428 |
+
|
| 429 |
+
# The way we compute split the input in `_get_chunked_inputs`,
|
| 430 |
+
# we may get a tensor with `0` batch-size. We skip any computation
|
| 431 |
+
# in that case.
|
| 432 |
+
# Eg.
|
| 433 |
+
# >>> chunk_size = 1
|
| 434 |
+
# >>> batch_size = 6
|
| 435 |
+
# >>> t = torch.zeros(batch_size, 1)
|
| 436 |
+
# >>> t.tensor_split([1, 2, 3, 4, 5, 6])
|
| 437 |
+
# (tensor([[0.]]), tensor([[0.]]), tensor([[0.]]), tensor([[0.]]),
|
| 438 |
+
# tensor([[0.]]), tensor([[0.]]), tensor([], size=(0, 1)))
|
| 439 |
+
if batch_size == 0:
|
| 440 |
+
continue
|
| 441 |
+
|
| 442 |
+
if rs is not None:
|
| 443 |
+
torch.set_rng_state(rs)
|
| 444 |
+
chunks_output.append(
|
| 445 |
+
_flat_vmap(
|
| 446 |
+
func,
|
| 447 |
+
batch_size,
|
| 448 |
+
flat_in_dims,
|
| 449 |
+
flat_args,
|
| 450 |
+
args_spec,
|
| 451 |
+
out_dims,
|
| 452 |
+
randomness,
|
| 453 |
+
**kwargs,
|
| 454 |
+
)
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
flat_output_chunks, arg_spec = _flatten_chunks_output(chunks_output)
|
| 458 |
+
|
| 459 |
+
# chunked output tensors are held by both `flat_output_chunks` and `chunks_output`.
|
| 460 |
+
# eagerly remove the reference from `chunks_output`.
|
| 461 |
+
del chunks_output
|
| 462 |
+
|
| 463 |
+
# concat chunks on out_dim
|
| 464 |
+
# Note: We use cast since flat_output_chunks is modified in _concat_chunked_outputs
|
| 465 |
+
# to set elements to None after processing
|
| 466 |
+
flat_output = _concat_chunked_outputs(
|
| 467 |
+
out_dims, arg_spec, cast(list[tuple[Any, ...] | None], flat_output_chunks)
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
# finally unflatten the output
|
| 471 |
+
return tree_unflatten(flat_output, arg_spec)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
# Vmap refactored helper functions:
|
| 475 |
+
def _check_randomness_arg(randomness: str) -> None:
|
| 476 |
+
if randomness not in ["error", "different", "same"]:
|
| 477 |
+
raise RuntimeError(
|
| 478 |
+
f"Only allowed values for randomness are 'error', 'different', or 'same'. Got {randomness}"
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
@contextlib.contextmanager
|
| 483 |
+
def vmap_increment_nesting(
|
| 484 |
+
batch_size: int, randomness: str
|
| 485 |
+
) -> Generator[int, None, None]:
|
| 486 |
+
try:
|
| 487 |
+
vmap_level = _vmap_increment_nesting(batch_size, randomness)
|
| 488 |
+
yield vmap_level
|
| 489 |
+
finally:
|
| 490 |
+
_vmap_decrement_nesting()
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def _flat_vmap(
|
| 494 |
+
func: Callable[..., Tensor | tuple[Tensor, ...]],
|
| 495 |
+
batch_size: int,
|
| 496 |
+
flat_in_dims: list[int | None],
|
| 497 |
+
flat_args: list[Any],
|
| 498 |
+
args_spec: TreeSpec,
|
| 499 |
+
out_dims: out_dims_t,
|
| 500 |
+
randomness: str,
|
| 501 |
+
**kwargs: Any,
|
| 502 |
+
) -> Any:
|
| 503 |
+
with vmap_increment_nesting(batch_size, randomness) as vmap_level:
|
| 504 |
+
batched_inputs = _create_batched_inputs(
|
| 505 |
+
flat_in_dims, flat_args, vmap_level, args_spec
|
| 506 |
+
)
|
| 507 |
+
batched_outputs = func(*batched_inputs, **kwargs)
|
| 508 |
+
return _unwrap_batched(batched_outputs, out_dims, vmap_level, batch_size, func)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
# `restore_vmap` is a private helper function. It is vmap but has the following
|
| 512 |
+
# differences:
|
| 513 |
+
# - instead of returning outputs, it returns an (outputs, out_dims) tuple.
|
| 514 |
+
# out_dims is a pytree of same shape as outputs and contains Optional[int]
|
| 515 |
+
# specifying where the vmapped dimension, if it exists, is in the corresponding output.
|
| 516 |
+
# - does no validation on in_dims or inputs (vmap expects at least one Tensor to be vmapped).
|
| 517 |
+
# restore_vmap allows for no inputs to have the vmap dimension
|
| 518 |
+
# - does no validation on outputs (vmap expects only Tensor outputs)
|
| 519 |
+
# restore_vmap allows for return of arbitrary outputs (not just Tensors)
|
| 520 |
+
#
|
| 521 |
+
# The TL;DR is that restore_vmap is more general than vmap and has a slightly
|
| 522 |
+
# different API. The relaxations are so that we can "pause" vmap in the middle
|
| 523 |
+
# of its execution and then "restore" it later (this is what we do in
|
| 524 |
+
# the generate_vmap_rule=True implementation of autograd.Function).
|
| 525 |
+
#
|
| 526 |
+
# restore_vmap can be technically used in the implementation of vmap, but doing
|
| 527 |
+
# that refactor is a bit technically challenging because:
|
| 528 |
+
# - vmap couples the tensor-wrapping code with error checking
|
| 529 |
+
# - vmap's tensor unwrapping code is in C++; we would need to rewrite part of it
|
| 530 |
+
# in python because it overlaps with unwrap_batched
|
| 531 |
+
def restore_vmap(
|
| 532 |
+
func: Callable[..., _R], in_dims: in_dims_t, batch_size: int, randomness: str
|
| 533 |
+
) -> Callable[..., tuple[Any, Any]]:
|
| 534 |
+
def inner(*args: Any, **kwargs: Any) -> tuple[Any, Any]:
|
| 535 |
+
with vmap_increment_nesting(batch_size, randomness) as vmap_level:
|
| 536 |
+
batched_inputs = wrap_batched(args, in_dims, vmap_level)
|
| 537 |
+
batched_outputs = func(*batched_inputs, **kwargs)
|
| 538 |
+
return unwrap_batched(batched_outputs, vmap_level)
|
| 539 |
+
|
| 540 |
+
return inner
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def wrap_batched(
|
| 544 |
+
args: tuple[Any, ...], bdims: in_dims_t, level: int
|
| 545 |
+
) -> tuple[Any, ...]:
|
| 546 |
+
flat_args, spec = tree_flatten(args)
|
| 547 |
+
flat_bdims = _broadcast_to_and_flatten(bdims, spec)
|
| 548 |
+
if flat_bdims is None:
|
| 549 |
+
raise AssertionError("flat_bdims must not be None")
|
| 550 |
+
result = _create_batched_inputs(flat_bdims, flat_args, level, spec)
|
| 551 |
+
return result
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def unwrap_batched(args: Any, level: int) -> tuple[Any, Any]:
|
| 555 |
+
flat_args, spec = tree_flatten(args)
|
| 556 |
+
if len(flat_args) == 0:
|
| 557 |
+
return args, ()
|
| 558 |
+
result = [
|
| 559 |
+
(
|
| 560 |
+
torch._C._functorch._unwrap_batched(arg, level)
|
| 561 |
+
if isinstance(arg, torch.Tensor)
|
| 562 |
+
else (arg, None)
|
| 563 |
+
)
|
| 564 |
+
for arg in flat_args
|
| 565 |
+
]
|
| 566 |
+
output, bdims = zip(*result)
|
| 567 |
+
return tree_unflatten(output, spec), tree_unflatten(bdims, spec)
|
venv/lib/python3.14/site-packages/torch/_guards.py
ADDED
|
@@ -0,0 +1,1536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import dataclasses
|
| 5 |
+
import enum
|
| 6 |
+
import functools
|
| 7 |
+
import logging
|
| 8 |
+
import re
|
| 9 |
+
import threading
|
| 10 |
+
import traceback
|
| 11 |
+
import unittest.mock
|
| 12 |
+
import weakref
|
| 13 |
+
from abc import abstractmethod
|
| 14 |
+
from collections import defaultdict
|
| 15 |
+
from contextlib import contextmanager
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from typing import Any, Generic, NamedTuple, overload, TYPE_CHECKING, TypeVar
|
| 18 |
+
from typing_extensions import dataclass_transform
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch.utils import _pytree as pytree
|
| 22 |
+
from torch.utils._ordered_set import OrderedSet
|
| 23 |
+
from torch.utils._python_dispatch import is_traceable_wrapper_subclass
|
| 24 |
+
from torch.utils._traceback import CapturedTraceback, format_frame
|
| 25 |
+
from torch.utils.weak import WeakTensorKeyDictionary
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
log = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if TYPE_CHECKING:
|
| 32 |
+
from collections.abc import Callable, Generator, Iterator
|
| 33 |
+
from types import CodeType
|
| 34 |
+
|
| 35 |
+
import sympy
|
| 36 |
+
|
| 37 |
+
from torch._dynamo.backends.distributed import DDPOptimizerContext
|
| 38 |
+
from torch._dynamo.codegen import PyCodegen
|
| 39 |
+
from torch._dynamo.guards import GuardCheckSpec
|
| 40 |
+
from torch._functorch._aot_autograd.schemas import ViewAndMutationMeta
|
| 41 |
+
from torch._higher_order_ops.invoke_subgraph import NestedCompileRegionOptions
|
| 42 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
"""
|
| 46 |
+
torch._guards is the definitional source of truth for general purpose guard structures.
|
| 47 |
+
|
| 48 |
+
An important thing to keep in mind here is the preservation of layering. There should be no dynamo notions,
|
| 49 |
+
and no guard installation notions here.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
COMPILE_ID_PATTERN = re.compile(r"^(?P<frame_id>\d+)/(?P<frame_compile_id>\d+)$")
|
| 53 |
+
CA_COMPILE_ID_PATTERN = re.compile(
|
| 54 |
+
r"^!(?P<compiled_autograd_id>\d+)(?:/(?P<frame_id>\d+)/(?P<frame_compile_id>\d+))?$"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# [Note: Updating CompiledId]
|
| 58 |
+
#
|
| 59 |
+
# CompiledId represents a unique program-level identifier, and we want to keep that
|
| 60 |
+
# property as the codebase evolves. This property is relied on even outside of the pytorch
|
| 61 |
+
# repo, e.g. tlparse or other internal tooling. The in-memory format can be freely changed,
|
| 62 |
+
# as those dependencies only consume the string serialization.
|
| 63 |
+
#
|
| 64 |
+
# The string form should be:
|
| 65 |
+
# 1. Program-level uid: CompileId can uniquely identify a compiled graph.
|
| 66 |
+
# 2. Storage efficient: This object is logged in nearly every entry. We should elide symbols when possible.
|
| 67 |
+
# 3. Compact: The string form is directly displayed by some tools. Special symbols are okay.
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
| 71 |
+
class CompileId:
|
| 72 |
+
frame_id: int | None
|
| 73 |
+
# This id is per-frame, and counts how many times we've compiled this
|
| 74 |
+
# frame. This could have been a global id but having this be per-frame
|
| 75 |
+
# gives you a better intuitive sense for how many recompiles have occurred
|
| 76 |
+
# so far.
|
| 77 |
+
frame_compile_id: int | None
|
| 78 |
+
|
| 79 |
+
# torch.compiling a compiled autograd graph
|
| 80 |
+
compiled_autograd_id: int | None = None
|
| 81 |
+
|
| 82 |
+
# TODO: consider also tracking the recompilation count
|
| 83 |
+
# See Note: Updating CompileId
|
| 84 |
+
|
| 85 |
+
def __str__(self) -> str:
|
| 86 |
+
# NOTE: Keep this in sync with both from_string and the tlparse repo
|
| 87 |
+
if self.compiled_autograd_id is not None:
|
| 88 |
+
if (self.frame_id is None) != (self.frame_compile_id is None):
|
| 89 |
+
raise AssertionError(
|
| 90 |
+
f"frame_id and frame_compile_id must both be None or both be set, "
|
| 91 |
+
f"got frame_id={self.frame_id}, frame_compile_id={self.frame_compile_id}"
|
| 92 |
+
)
|
| 93 |
+
frame_str = ""
|
| 94 |
+
if self.frame_id is not None:
|
| 95 |
+
frame_str = f"/{self.frame_id}/{self.frame_compile_id}"
|
| 96 |
+
|
| 97 |
+
return f"!{self.compiled_autograd_id}{frame_str}"
|
| 98 |
+
else:
|
| 99 |
+
if self.frame_id is None or self.frame_compile_id is None:
|
| 100 |
+
raise AssertionError(
|
| 101 |
+
f"frame_id and frame_compile_id must not be None, "
|
| 102 |
+
f"got frame_id={self.frame_id}, frame_compile_id={self.frame_compile_id}"
|
| 103 |
+
)
|
| 104 |
+
return f"{self.frame_id}/{self.frame_compile_id}"
|
| 105 |
+
|
| 106 |
+
@classmethod
|
| 107 |
+
def from_string(cls, compile_id: str | None) -> CompileId | None:
|
| 108 |
+
"""
|
| 109 |
+
Factory method that creates a CompileId from its string representation.
|
| 110 |
+
Keep this in sync with the __str__ method.
|
| 111 |
+
"""
|
| 112 |
+
if compile_id is None:
|
| 113 |
+
return None
|
| 114 |
+
try:
|
| 115 |
+
for pattern in (COMPILE_ID_PATTERN, CA_COMPILE_ID_PATTERN):
|
| 116 |
+
if match := pattern.match(compile_id):
|
| 117 |
+
groups = match.groupdict()
|
| 118 |
+
for k, v in groups.items():
|
| 119 |
+
if v is not None:
|
| 120 |
+
groups[k] = int(v)
|
| 121 |
+
return cls(**groups) # type: ignore[arg-type]
|
| 122 |
+
else:
|
| 123 |
+
raise ValueError
|
| 124 |
+
|
| 125 |
+
except Exception as e:
|
| 126 |
+
raise ValueError(f"Invalid compile_id '{compile_id}'") from e
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class TraceId(NamedTuple):
|
| 130 |
+
compile_id: CompileId
|
| 131 |
+
# This starts off as 0, and every time we restart analysis it goes
|
| 132 |
+
# up by one
|
| 133 |
+
attempt: int
|
| 134 |
+
|
| 135 |
+
def __str__(self) -> str:
|
| 136 |
+
# Keep this in sync with tlparse repo
|
| 137 |
+
if self.attempt == 0:
|
| 138 |
+
return str(self.compile_id)
|
| 139 |
+
else:
|
| 140 |
+
return f"{self.compile_id}_{self.attempt}"
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class GuardSource(enum.Enum):
|
| 144 |
+
LOCAL = 0
|
| 145 |
+
GLOBAL = 1
|
| 146 |
+
LOCAL_SPECIALIZED_NN_MODULE = 2
|
| 147 |
+
GLOBAL_SPECIALIZED_NN_MODULE = 3
|
| 148 |
+
CONSTANT = 4
|
| 149 |
+
RANDOM_VALUE = 5
|
| 150 |
+
SHAPE_ENV = 6
|
| 151 |
+
LOCAL_FSDP_MODULE = 7
|
| 152 |
+
GLOBAL_FSDP_MODULE = 8
|
| 153 |
+
BACKWARD_STATE = 9
|
| 154 |
+
EPHEMERAL = 10
|
| 155 |
+
SYNTHETIC_LOCAL = 11
|
| 156 |
+
LOCAL_UNSPECIALIZED_NN_MODULE = 12
|
| 157 |
+
GLOBAL_UNSPECIALIZED_NN_MODULE = 13
|
| 158 |
+
LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 14
|
| 159 |
+
GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 15
|
| 160 |
+
TEMP_LOCAL = 16
|
| 161 |
+
|
| 162 |
+
def is_fsdp_module(self) -> bool:
|
| 163 |
+
return self in (GuardSource.GLOBAL_FSDP_MODULE, GuardSource.LOCAL_FSDP_MODULE)
|
| 164 |
+
|
| 165 |
+
def is_specialized_nn_module(self) -> bool:
|
| 166 |
+
import torch._dynamo.config as config
|
| 167 |
+
|
| 168 |
+
if config._unsafe_skip_fsdp_module_guards:
|
| 169 |
+
return (
|
| 170 |
+
self
|
| 171 |
+
in (
|
| 172 |
+
GuardSource.GLOBAL_SPECIALIZED_NN_MODULE,
|
| 173 |
+
GuardSource.LOCAL_SPECIALIZED_NN_MODULE,
|
| 174 |
+
)
|
| 175 |
+
or self.is_fsdp_module()
|
| 176 |
+
)
|
| 177 |
+
return self in (
|
| 178 |
+
GuardSource.GLOBAL_SPECIALIZED_NN_MODULE,
|
| 179 |
+
GuardSource.LOCAL_SPECIALIZED_NN_MODULE,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
def is_unspecialized_nn_module(self) -> bool:
|
| 183 |
+
return self in (
|
| 184 |
+
GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE,
|
| 185 |
+
GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE,
|
| 186 |
+
GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
|
| 187 |
+
GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def is_unspecialized_builtin_nn_module(self) -> bool:
|
| 191 |
+
return self in (
|
| 192 |
+
GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
|
| 193 |
+
GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
def is_local(self) -> bool:
|
| 197 |
+
return self in (
|
| 198 |
+
GuardSource.LOCAL,
|
| 199 |
+
GuardSource.LOCAL_SPECIALIZED_NN_MODULE,
|
| 200 |
+
GuardSource.LOCAL_FSDP_MODULE,
|
| 201 |
+
GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE,
|
| 202 |
+
GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
"""
|
| 207 |
+
Base class for a "GuardBuilder" role.
|
| 208 |
+
|
| 209 |
+
The GuardBuilderBase role is to represent a scope within which to build a guard. The name is a little
|
| 210 |
+
confusing, as its not a builder, but for the sake of avoiding a lot of renames and keeping the original reference
|
| 211 |
+
to torchdynamo's GuardBuilder.
|
| 212 |
+
|
| 213 |
+
Note: create_fn is invoked with a GuardBuilderBase and a Guard. A GuardBuilder is chosen based
|
| 214 |
+
on GuardSource's select function.
|
| 215 |
+
|
| 216 |
+
There is value in keeping this GuardBuilderBase empty to keep layering clean.
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class GuardBuilderBase:
|
| 221 |
+
pass
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
@dataclasses.dataclass(frozen=True)
|
| 225 |
+
class SLoc:
|
| 226 |
+
framework_loc: traceback.FrameSummary | str | None
|
| 227 |
+
maybe_user_loc: str | None
|
| 228 |
+
|
| 229 |
+
def __str__(self) -> str:
|
| 230 |
+
floc = (
|
| 231 |
+
self.framework_loc
|
| 232 |
+
if isinstance(self.framework_loc, str)
|
| 233 |
+
else format_frame(self.framework_loc)
|
| 234 |
+
)
|
| 235 |
+
if self.maybe_user_loc is not None:
|
| 236 |
+
return f"{self.maybe_user_loc} ({floc})"
|
| 237 |
+
else:
|
| 238 |
+
return f"({floc})"
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
class ShapeGuard(NamedTuple):
|
| 242 |
+
expr: sympy.logic.boolalg.Boolean
|
| 243 |
+
sloc: SLoc
|
| 244 |
+
size_oblivious: bool
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@dataclasses.dataclass(slots=True)
|
| 248 |
+
class Guard:
|
| 249 |
+
# originating_source is the source that called the make_guard method to
|
| 250 |
+
# construct this guard object. The property name specifies what exactly it
|
| 251 |
+
# is the guard is guarding on. The meaning of the name is dependent on the
|
| 252 |
+
# create_fn; you must look at the use-site inside create_fn to know what
|
| 253 |
+
# name means.
|
| 254 |
+
#
|
| 255 |
+
# That being said, although you might think this is just a "name", name is
|
| 256 |
+
# usually an arbitrary Python expression that will be evaluated with all
|
| 257 |
+
# globals (and locals, if you create a LOCAL guard) to extract the Python
|
| 258 |
+
# object that we want to perform guard tests on. This evaluation
|
| 259 |
+
# typically happens in GuardBuilder.eval. In these cases, name is
|
| 260 |
+
# typically produced by originating_source.name (not to be confused with
|
| 261 |
+
# GuardSource - the property source).
|
| 262 |
+
#
|
| 263 |
+
# Occasionally, name is not a valid Python expression; sometimes
|
| 264 |
+
# it is meaningless. Example create_fns that are like this include
|
| 265 |
+
# GRAD_MODE and SHAPE_ENV.
|
| 266 |
+
originating_source: Source
|
| 267 |
+
create_fn: Callable[[GuardBuilderBase, Guard], None]
|
| 268 |
+
|
| 269 |
+
# Export only. These values are written to at time of guard check_fn creation.
|
| 270 |
+
guard_types: list[str] | None = None
|
| 271 |
+
code_list: list[str] | None = None
|
| 272 |
+
obj_weakref: object | None = None
|
| 273 |
+
guarded_class_weakref: weakref.ReferenceType[Any] | None = None
|
| 274 |
+
|
| 275 |
+
stack: CapturedTraceback | None = None
|
| 276 |
+
user_stack: traceback.StackSummary | None = None
|
| 277 |
+
_hash: int | None = None
|
| 278 |
+
_unserializable: bool = False
|
| 279 |
+
|
| 280 |
+
def __hash__(self) -> int:
|
| 281 |
+
if self._hash is None:
|
| 282 |
+
self._hash = hash((self.name, self.source, id(self.create_fn)))
|
| 283 |
+
return self._hash
|
| 284 |
+
|
| 285 |
+
def sort_key(self) -> tuple[bool, int, int, str, int]:
|
| 286 |
+
# Put the duplicate input guards at the end. The duplicate guards have
|
| 287 |
+
# two sources while guard.name only considers one source.
|
| 288 |
+
|
| 289 |
+
is_duplicate_input = (
|
| 290 |
+
isinstance(self.create_fn, functools.partial)
|
| 291 |
+
and self.create_fn.func is torch._dynamo.guards.GuardBuilder.DUPLICATE_INPUT
|
| 292 |
+
)
|
| 293 |
+
return (
|
| 294 |
+
is_duplicate_input,
|
| 295 |
+
self.source.value if self.source else -1,
|
| 296 |
+
len(self.name),
|
| 297 |
+
self.name,
|
| 298 |
+
self.inner_create_fn().__code__.co_firstlineno,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
def __lt__(self, other: Guard) -> bool:
|
| 302 |
+
return self.sort_key() < other.sort_key()
|
| 303 |
+
|
| 304 |
+
def inner_create_fn(self) -> Callable[[GuardBuilderBase, Guard], Any]:
|
| 305 |
+
if isinstance(self.create_fn, functools.partial):
|
| 306 |
+
return self.create_fn.func
|
| 307 |
+
else:
|
| 308 |
+
return self.create_fn
|
| 309 |
+
|
| 310 |
+
@property
|
| 311 |
+
def name(self) -> str:
|
| 312 |
+
return self.originating_source.name
|
| 313 |
+
|
| 314 |
+
@property
|
| 315 |
+
def source(self) -> GuardSource:
|
| 316 |
+
return self.originating_source.guard_source
|
| 317 |
+
|
| 318 |
+
@staticmethod
|
| 319 |
+
def weakref_to_str(obj_weakref: object) -> str:
|
| 320 |
+
"""
|
| 321 |
+
This is a workaround of a Python weakref bug.
|
| 322 |
+
|
| 323 |
+
`obj_weakref` is instance returned by `weakref.ref`,
|
| 324 |
+
`str(obj_weakref)` is buggy if the original obj overrides __getattr__, e.g:
|
| 325 |
+
|
| 326 |
+
class MyConfig(dict):
|
| 327 |
+
def __getattr__(self, x):
|
| 328 |
+
return self[x]
|
| 329 |
+
|
| 330 |
+
obj = MyConfig(offset=5)
|
| 331 |
+
obj_weakref = weakref.ref(obj)
|
| 332 |
+
str(obj_weakref) # raise error: KeyError: '__name__'
|
| 333 |
+
"""
|
| 334 |
+
if isinstance(obj_weakref, weakref.ReferenceType):
|
| 335 |
+
obj = obj_weakref()
|
| 336 |
+
if obj is not None:
|
| 337 |
+
return f"<weakref at {hex(id(obj_weakref))}; to '{obj.__class__.__name__}' at {hex(id(obj))}>"
|
| 338 |
+
else:
|
| 339 |
+
return f"<weakref at {hex(id(obj_weakref))}; dead>"
|
| 340 |
+
else:
|
| 341 |
+
return str(obj_weakref)
|
| 342 |
+
|
| 343 |
+
def __repr__(self) -> str:
|
| 344 |
+
s = f"""
|
| 345 |
+
{self.source.name.lower() if self.source else ""} {repr(self.name)} {self.inner_create_fn().__name__}
|
| 346 |
+
{{
|
| 347 |
+
'guard_types': {self.guard_types},
|
| 348 |
+
'code': {self.code_list},
|
| 349 |
+
'obj_weakref': {self.weakref_to_str(self.obj_weakref)}
|
| 350 |
+
'guarded_class': {self.guarded_class_weakref}
|
| 351 |
+
}}
|
| 352 |
+
"""
|
| 353 |
+
return s
|
| 354 |
+
|
| 355 |
+
def __str__(self) -> str:
|
| 356 |
+
output = f"Name: {repr(self.name)}\n"
|
| 357 |
+
source = self.source.name.lower() if self.source else ""
|
| 358 |
+
output += f" Source: {source}\n"
|
| 359 |
+
output += f" Create Function: {self.inner_create_fn().__name__}\n"
|
| 360 |
+
output += f" Guard Types: {self.guard_types}\n"
|
| 361 |
+
output += f" Code List: {self.code_list}\n"
|
| 362 |
+
output += f" Object Weakref: {self.weakref_to_str(self.obj_weakref)}\n"
|
| 363 |
+
output += f" Guarded Class Weakref: {self.guarded_class_weakref}\n"
|
| 364 |
+
return output
|
| 365 |
+
|
| 366 |
+
def create(self, builder: GuardBuilderBase) -> Any:
|
| 367 |
+
try:
|
| 368 |
+
return self.create_fn(builder, self)
|
| 369 |
+
except Exception:
|
| 370 |
+
log.exception("Error while creating guard:\n%s", str(self).rstrip())
|
| 371 |
+
if self.stack:
|
| 372 |
+
log.error("Created at:\n%s", "".join(self.stack.format()[-4:]).rstrip())
|
| 373 |
+
raise
|
| 374 |
+
|
| 375 |
+
def is_specialized_nn_module(self) -> bool:
|
| 376 |
+
return self.source.is_specialized_nn_module()
|
| 377 |
+
|
| 378 |
+
def is_fsdp_module(self) -> bool:
|
| 379 |
+
return self.source.is_fsdp_module()
|
| 380 |
+
|
| 381 |
+
def is_local(self) -> bool:
|
| 382 |
+
return self.source.is_local()
|
| 383 |
+
|
| 384 |
+
def create_fn_name(self) -> str:
|
| 385 |
+
if isinstance(self.create_fn, functools.partial):
|
| 386 |
+
create_fn = self.create_fn.func # type: ignore[attr-defined]
|
| 387 |
+
else:
|
| 388 |
+
create_fn = self.create_fn
|
| 389 |
+
return create_fn.__name__
|
| 390 |
+
|
| 391 |
+
def set_export_info(
|
| 392 |
+
self,
|
| 393 |
+
guard_type: str,
|
| 394 |
+
guarded_class: weakref.ReferenceType[Any] | None,
|
| 395 |
+
code_list: list[str],
|
| 396 |
+
obj_weakref: object,
|
| 397 |
+
) -> None:
|
| 398 |
+
if not self.guard_types:
|
| 399 |
+
self.guard_types = []
|
| 400 |
+
|
| 401 |
+
self.guard_types.append(guard_type)
|
| 402 |
+
|
| 403 |
+
if self.guarded_class_weakref not in (guarded_class, None):
|
| 404 |
+
raise AssertionError(
|
| 405 |
+
f"Guarded class id must be identical, or None, "
|
| 406 |
+
f"got {self.guarded_class_weakref} vs {guarded_class}"
|
| 407 |
+
)
|
| 408 |
+
self.guarded_class_weakref = guarded_class
|
| 409 |
+
|
| 410 |
+
if not self.code_list:
|
| 411 |
+
self.code_list = code_list
|
| 412 |
+
else:
|
| 413 |
+
self.code_list.extend(code_list)
|
| 414 |
+
|
| 415 |
+
# Some objects are ephemeral, e.g., list[slice(1, 2)]. If we have
|
| 416 |
+
# multiple guards on the same object, the weakref can die between the
|
| 417 |
+
# invocation of set_export_info calls. So a dead weakref is also
|
| 418 |
+
# acceptable.
|
| 419 |
+
is_valid = (
|
| 420 |
+
self.obj_weakref in (obj_weakref, None)
|
| 421 |
+
or callable(self.obj_weakref)
|
| 422 |
+
and self.obj_weakref() is None
|
| 423 |
+
)
|
| 424 |
+
if not is_valid:
|
| 425 |
+
raise AssertionError(
|
| 426 |
+
f"Guarded object must be identical, None or ephemeral (dead weakref), "
|
| 427 |
+
f"got {self.obj_weakref} vs {obj_weakref}"
|
| 428 |
+
)
|
| 429 |
+
self.obj_weakref = obj_weakref
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
T = TypeVar("T")
|
| 433 |
+
|
| 434 |
+
"""
|
| 435 |
+
Parent structure for guard env expressions.
|
| 436 |
+
A GuardEnvExpr can have any subtype.
|
| 437 |
+
Note: All subtypes must be handled exhaustively in
|
| 438 |
+
torch._dynamo.guards._parse_guard_env_guards to avoid a RuntimeError.
|
| 439 |
+
"""
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
@dataclasses.dataclass(frozen=True)
|
| 443 |
+
class GuardEnvExpr:
|
| 444 |
+
pass
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
"""
|
| 448 |
+
A class representing a pair of duplicate inputs.
|
| 449 |
+
input_pos_a and input_pos_b are input positions we have deduped.
|
| 450 |
+
"""
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
@dataclasses.dataclass(frozen=True)
|
| 454 |
+
class DuplicateInputs(GuardEnvExpr):
|
| 455 |
+
input_source_a: Source
|
| 456 |
+
input_source_b: Source
|
| 457 |
+
|
| 458 |
+
def __post_init__(self) -> None:
|
| 459 |
+
if self.input_source_a == self.input_source_b:
|
| 460 |
+
raise AssertionError(
|
| 461 |
+
f"input_source_a and input_source_b must be different, "
|
| 462 |
+
f"got {self.input_source_a}"
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
"""
|
| 467 |
+
A class representing storage overlap relations among inputs that aliases the same storage.
|
| 468 |
+
|
| 469 |
+
Given that a set of tensors alias the same storage, this guard checks whether they actually
|
| 470 |
+
have overlapping storages.
|
| 471 |
+
|
| 472 |
+
While non_overlapping_sources represent input tensors that definitely don't have any storage
|
| 473 |
+
overlapping with any other input, overlapping_sources represent tensors that either:
|
| 474 |
+
|
| 475 |
+
1. Do overlap some other input tensor
|
| 476 |
+
2. Might not overlap some other input tensor, but we are not sure
|
| 477 |
+
"""
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
@dataclasses.dataclass(frozen=True)
|
| 481 |
+
class StorageOverlap(GuardEnvExpr):
|
| 482 |
+
overlapping_sources: list[Source]
|
| 483 |
+
non_overlapping_sources: list[Source]
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
"""
|
| 487 |
+
Checkpointable is an interface for driving state snapshotting, left purposely vague for now.
|
| 488 |
+
|
| 489 |
+
copy_graphstate() -> T, a somewhat legacy name, is expected to emit a snapshot of any type that
|
| 490 |
+
can also be taken in at restore_graphstate(T) calls.
|
| 491 |
+
|
| 492 |
+
When to snapshot, is, at the moment, an implementation detail of upstream callers. Checkpointable
|
| 493 |
+
does not provide any guarantees around consistency, idempotency, or safety of calling its APIs, yet.
|
| 494 |
+
|
| 495 |
+
In the future, it will have a closer coupling to a generic Checkpoint management system.
|
| 496 |
+
"""
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
class Checkpointable(Generic[T]):
|
| 500 |
+
@abstractmethod
|
| 501 |
+
def copy_graphstate(self) -> T: ...
|
| 502 |
+
|
| 503 |
+
@abstractmethod
|
| 504 |
+
def restore_graphstate(self, state: T) -> None: ...
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
class GuardsCheckpointState:
|
| 508 |
+
"""
|
| 509 |
+
The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext
|
| 510 |
+
"""
|
| 511 |
+
|
| 512 |
+
dynamo_guards: OrderedSet[Guard]
|
| 513 |
+
|
| 514 |
+
def __init__(self, dynamo_guards: OrderedSet[Guard]) -> None:
|
| 515 |
+
self.dynamo_guards = dynamo_guards
|
| 516 |
+
|
| 517 |
+
def diff(self, other: GuardsCheckpointState) -> OrderedSet[Guard] | None:
|
| 518 |
+
"""
|
| 519 |
+
Produces a delta against another GuardsCheckpointState.
|
| 520 |
+
|
| 521 |
+
Returns None if no delta is found, otherwise, return an OrderedSet() of mismatched
|
| 522 |
+
Guard type objects.
|
| 523 |
+
"""
|
| 524 |
+
r = self.dynamo_guards.difference(other.dynamo_guards)
|
| 525 |
+
if len(r) == 0:
|
| 526 |
+
return None
|
| 527 |
+
return r
|
| 528 |
+
|
| 529 |
+
def __eq__(self, other: object) -> bool:
|
| 530 |
+
if not isinstance(other, GuardsCheckpointState):
|
| 531 |
+
return False
|
| 532 |
+
return self.diff(other) is None
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
class ModuleContextCheckpointState:
|
| 536 |
+
nn_modules: dict[str, torch.nn.Module] = {}
|
| 537 |
+
|
| 538 |
+
def __init__(self, nn_modules: dict[str, torch.nn.Module]) -> None:
|
| 539 |
+
self.nn_modules = nn_modules
|
| 540 |
+
|
| 541 |
+
def diff(self, other: ModuleContextCheckpointState) -> set[str] | None:
|
| 542 |
+
"""
|
| 543 |
+
Produces a delta against another ModuleContextCheckpointState.
|
| 544 |
+
|
| 545 |
+
Returns None if no delta is found, otherwise, return a set() of mismatched
|
| 546 |
+
module key names.
|
| 547 |
+
"""
|
| 548 |
+
r = set(self.nn_modules.keys()).difference(set(other.nn_modules.keys()))
|
| 549 |
+
if len(r) == 0:
|
| 550 |
+
return None
|
| 551 |
+
return r
|
| 552 |
+
|
| 553 |
+
def __eq__(self, other: object) -> bool:
|
| 554 |
+
if not isinstance(other, ModuleContextCheckpointState):
|
| 555 |
+
return False
|
| 556 |
+
return self.diff(other) is None
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
class ModuleContext(Checkpointable[ModuleContextCheckpointState]):
|
| 560 |
+
def __init__(self) -> None:
|
| 561 |
+
self.nn_modules: dict[str, Any] = {}
|
| 562 |
+
|
| 563 |
+
def copy_graphstate(self) -> ModuleContextCheckpointState:
|
| 564 |
+
return ModuleContextCheckpointState(dict(self.nn_modules))
|
| 565 |
+
|
| 566 |
+
def restore_graphstate(self, state: ModuleContextCheckpointState) -> None:
|
| 567 |
+
if not isinstance(state, ModuleContextCheckpointState):
|
| 568 |
+
raise AssertionError(
|
| 569 |
+
f"expected ModuleContextCheckpointState, got {type(state)}"
|
| 570 |
+
)
|
| 571 |
+
self.nn_modules = state.nn_modules
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
class GlobalContextCheckpointState:
|
| 575 |
+
global_state: dict[str, tuple[Callable, Any]] = {}
|
| 576 |
+
|
| 577 |
+
def __init__(self, global_states: dict[str, tuple[Callable, Any]]) -> None:
|
| 578 |
+
self.global_state = global_states
|
| 579 |
+
|
| 580 |
+
def diff(self, other: GlobalContextCheckpointState) -> set[str] | None:
|
| 581 |
+
"""
|
| 582 |
+
Produces a delta against another GlobalContextCheckpointState.
|
| 583 |
+
|
| 584 |
+
Returns None if no delta is found, otherwise, return a set() of mismatched
|
| 585 |
+
global key names.
|
| 586 |
+
"""
|
| 587 |
+
r = set(self.global_state.keys()).difference(set(other.global_state.keys()))
|
| 588 |
+
if len(r) == 0:
|
| 589 |
+
return None
|
| 590 |
+
return r
|
| 591 |
+
|
| 592 |
+
def __eq__(self, other: object) -> bool:
|
| 593 |
+
if not isinstance(other, GlobalContextCheckpointState):
|
| 594 |
+
return False
|
| 595 |
+
return self.diff(other) is None
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
class GlobalContext(Checkpointable[GlobalContextCheckpointState]):
|
| 599 |
+
"""
|
| 600 |
+
This keeps track of the global torch state during tracing of a function.
|
| 601 |
+
For example, torch.is_grad_enabled.
|
| 602 |
+
"""
|
| 603 |
+
|
| 604 |
+
_supported_global_states = {
|
| 605 |
+
"grad_enabled",
|
| 606 |
+
"autocast_enabled",
|
| 607 |
+
"autocast_cpu_enabled",
|
| 608 |
+
"autocast_gpu_dtype",
|
| 609 |
+
"autocast_cpu_dtype",
|
| 610 |
+
"autocast_cache_enabled",
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
def __init__(self) -> None:
|
| 614 |
+
self.global_state: dict[str, tuple[Callable, Any]] = {}
|
| 615 |
+
|
| 616 |
+
def copy_graphstate(self) -> GlobalContextCheckpointState:
|
| 617 |
+
return GlobalContextCheckpointState(self.global_state)
|
| 618 |
+
|
| 619 |
+
def restore_graphstate(self, state: GlobalContextCheckpointState) -> None:
|
| 620 |
+
if not isinstance(state, GlobalContextCheckpointState):
|
| 621 |
+
raise AssertionError(
|
| 622 |
+
f"expected GlobalContextCheckpointState, got {type(state)}"
|
| 623 |
+
)
|
| 624 |
+
self.global_state = state.global_state
|
| 625 |
+
if not (
|
| 626 |
+
len(self.global_state) == len(self._supported_global_states)
|
| 627 |
+
and set(self.global_state.keys()) == self._supported_global_states
|
| 628 |
+
):
|
| 629 |
+
raise AssertionError(
|
| 630 |
+
f"Global state mismatch: got keys {set(self.global_state.keys())}, "
|
| 631 |
+
f"expected {self._supported_global_states}"
|
| 632 |
+
)
|
| 633 |
+
for func, args in self.global_state.values():
|
| 634 |
+
func(args)
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
# Like a Set[Guard] but will record the user stack on all guards at the
|
| 638 |
+
# time they were installed at their destination
|
| 639 |
+
class GuardsSet:
|
| 640 |
+
def __init__(self, inner: OrderedSet[Guard] | None = None) -> None:
|
| 641 |
+
if inner is None:
|
| 642 |
+
self.inner: OrderedSet[Guard] = OrderedSet()
|
| 643 |
+
else:
|
| 644 |
+
self.inner = inner
|
| 645 |
+
# Map from source to list of guards with that source. Incrementally
|
| 646 |
+
# built in `add` method.
|
| 647 |
+
self.source_to_guards: defaultdict[Source, list[Guard]] = defaultdict(list)
|
| 648 |
+
for guard in self.inner:
|
| 649 |
+
self.track_guard_by_source(guard)
|
| 650 |
+
|
| 651 |
+
def track_guard_by_source(self, guard: Guard) -> None:
|
| 652 |
+
source = guard.originating_source
|
| 653 |
+
self.source_to_guards[source].append(guard)
|
| 654 |
+
|
| 655 |
+
def __iter__(self) -> Iterator[Guard]:
|
| 656 |
+
return iter(self.inner)
|
| 657 |
+
|
| 658 |
+
def __len__(self) -> int:
|
| 659 |
+
return len(self.inner)
|
| 660 |
+
|
| 661 |
+
# Subtraction along with bool is typically used to determine the delta of
|
| 662 |
+
# added guards between checkpoints for higher order ops
|
| 663 |
+
def __sub__(self, other: GuardsSet) -> GuardsSet:
|
| 664 |
+
return GuardsSet(self.inner - other.inner)
|
| 665 |
+
|
| 666 |
+
def __bool__(self) -> bool:
|
| 667 |
+
return bool(self.inner)
|
| 668 |
+
|
| 669 |
+
def clear(self) -> None:
|
| 670 |
+
self.inner = OrderedSet()
|
| 671 |
+
self.source_to_guards = defaultdict(list)
|
| 672 |
+
|
| 673 |
+
def add(
|
| 674 |
+
self, guard: Guard, *, collect_debug_stack: bool = True, skip: int = 0
|
| 675 |
+
) -> None:
|
| 676 |
+
if guard in self.inner:
|
| 677 |
+
return
|
| 678 |
+
if collect_debug_stack:
|
| 679 |
+
if guard.stack is None:
|
| 680 |
+
guard.stack = CapturedTraceback.extract(skip=1 + skip)
|
| 681 |
+
if guard.user_stack is None:
|
| 682 |
+
guard.user_stack = TracingContext.extract_stack()
|
| 683 |
+
self.inner.add(guard)
|
| 684 |
+
self.track_guard_by_source(guard)
|
| 685 |
+
|
| 686 |
+
def update(self, *others: set[Guard]) -> None:
|
| 687 |
+
for o in others:
|
| 688 |
+
for g in o:
|
| 689 |
+
self.add(g, skip=1)
|
| 690 |
+
|
| 691 |
+
def get_guards_for_source(self, source: Source) -> list[Guard]:
|
| 692 |
+
"""Return all guards with the given originating_source."""
|
| 693 |
+
return list(self.source_to_guards[source])
|
| 694 |
+
|
| 695 |
+
def remove_guards_with_source(self, source: Source) -> None:
|
| 696 |
+
"""Delete all guards that contains a given source"""
|
| 697 |
+
from ._dynamo.source import is_from_source
|
| 698 |
+
|
| 699 |
+
self.inner = OrderedSet(
|
| 700 |
+
g for g in self.inner if not is_from_source(g.originating_source, source)
|
| 701 |
+
)
|
| 702 |
+
# Rebuild the index since is_from_source walks the chain, so
|
| 703 |
+
# multiple source keys may need removal.
|
| 704 |
+
self.source_to_guards = defaultdict(list)
|
| 705 |
+
for guard in self.inner:
|
| 706 |
+
self.track_guard_by_source(guard)
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
"""
|
| 710 |
+
A GuardsContext is a checkpointable representation of all the guards in the current tracing
|
| 711 |
+
context. It's lifecycle is bound 1:1 to the tracing context, and it should never be instantiated
|
| 712 |
+
directly outside of it. For passing around internal state representations of this object,
|
| 713 |
+
prefer to extract them with copy_graphstate to produce a GuardsCheckpointState.
|
| 714 |
+
"""
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
class GuardsContext(Checkpointable[GuardsCheckpointState]):
|
| 718 |
+
def __init__(self) -> None:
|
| 719 |
+
self.dynamo_guards: GuardsSet = GuardsSet()
|
| 720 |
+
self.aotautograd_guards: list[GuardEnvExpr] = []
|
| 721 |
+
self.skip_install: bool = False
|
| 722 |
+
|
| 723 |
+
@contextlib.contextmanager
|
| 724 |
+
def skip_guard_install(self) -> Generator[None, None, None]:
|
| 725 |
+
old = self.skip_install
|
| 726 |
+
self.skip_install = True
|
| 727 |
+
try:
|
| 728 |
+
yield
|
| 729 |
+
finally:
|
| 730 |
+
self.skip_install = old
|
| 731 |
+
|
| 732 |
+
def copy_graphstate(self) -> GuardsCheckpointState:
|
| 733 |
+
return GuardsCheckpointState(OrderedSet(self.dynamo_guards.inner))
|
| 734 |
+
|
| 735 |
+
def restore_graphstate(self, state: GuardsCheckpointState) -> None:
|
| 736 |
+
# NB: "steals" the passed in state
|
| 737 |
+
if not isinstance(state, GuardsCheckpointState):
|
| 738 |
+
raise AssertionError(f"expected GuardsCheckpointState, got {type(state)}")
|
| 739 |
+
self.dynamo_guards = GuardsSet(state.dynamo_guards)
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
class HopSubgraphCache:
|
| 743 |
+
@abstractmethod
|
| 744 |
+
def add_dynamo_installed_submodule(
|
| 745 |
+
self, fn_code: CodeType, identifier: str
|
| 746 |
+
) -> None: ...
|
| 747 |
+
|
| 748 |
+
@abstractmethod
|
| 749 |
+
def get_dynamo_installed_submodules(self, fn_code: CodeType) -> list[str]: ...
|
| 750 |
+
|
| 751 |
+
@abstractmethod
|
| 752 |
+
def add_autograd_key_entry(self, identifier: str, key: Callable) -> None: ...
|
| 753 |
+
|
| 754 |
+
@abstractmethod
|
| 755 |
+
def get_autograd_key_entry(self, identifier: str) -> Callable | None: ...
|
| 756 |
+
|
| 757 |
+
@abstractmethod
|
| 758 |
+
def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None: ...
|
| 759 |
+
|
| 760 |
+
@abstractmethod
|
| 761 |
+
def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None: ...
|
| 762 |
+
|
| 763 |
+
@abstractmethod
|
| 764 |
+
def add_lazy_bwd_entry(
|
| 765 |
+
self,
|
| 766 |
+
identifier: str,
|
| 767 |
+
tangent_metadata: tuple[object],
|
| 768 |
+
gmod: torch.fx.GraphModule,
|
| 769 |
+
) -> int: ...
|
| 770 |
+
|
| 771 |
+
@abstractmethod
|
| 772 |
+
def get_lazy_bwd_entry(
|
| 773 |
+
self, identifier: str, tangent_metadata: tuple[object]
|
| 774 |
+
) -> tuple[torch.fx.GraphModule | None, int | None]: ...
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
@dataclass
|
| 778 |
+
class InvokeSubgraphReuseEntry:
|
| 779 |
+
body_name: str
|
| 780 |
+
body_gmod: torch.fx.GraphModule
|
| 781 |
+
config: NestedCompileRegionOptions | None
|
| 782 |
+
subgraph_input_mapping: list[
|
| 783 |
+
Any
|
| 784 |
+
] # list[LiftedArgOrigin] - defined in invoke_subgraph.py
|
| 785 |
+
single_tensor_output: bool
|
| 786 |
+
# Per-output tensor metadata (shape, stride, dtype, device, requires_grad)
|
| 787 |
+
# cached from the first trace so we can construct fresh FakeTensors on
|
| 788 |
+
# cache hit without re-running body_gmod.
|
| 789 |
+
output_metadata: list[
|
| 790 |
+
tuple[torch.Size, tuple[int, ...], torch.dtype, torch.device, bool]
|
| 791 |
+
]
|
| 792 |
+
# 1-1 mapping to flat_vts: source for each flattened arg/kwarg, or None if
|
| 793 |
+
# the VT has no source. On cache hit, we build a source replacement mapping
|
| 794 |
+
# (old arg sources → new arg sources) to rewrite captured variable sources
|
| 795 |
+
# for the current invocation.
|
| 796 |
+
arg_sources: list[Source | None]
|
| 797 |
+
# Number of user-visible outputs (from the function return value).
|
| 798 |
+
# The graph may have additional outputs from side-effect intermediates;
|
| 799 |
+
# stamp_out_subgraph uses this to return only the user-visible slice.
|
| 800 |
+
num_user_outputs: int = 0
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
@dataclass
|
| 804 |
+
class InvokeSubgraphReuseCondition:
|
| 805 |
+
# Per flattened input VT: (InputTag, metadata).
|
| 806 |
+
# (InputTag.TENSOR, TensorMetadata)
|
| 807 |
+
# (InputTag.SYMNODE, sym_num — same object implies same symbol)
|
| 808 |
+
# (InputTag.CONSTANT, value)
|
| 809 |
+
# (InputTag.MODULE, None)
|
| 810 |
+
# Tensor metadata is checked here because TENSOR_MATCH guards for
|
| 811 |
+
# subgraph inputs may already exist before tracing and thus won't
|
| 812 |
+
# appear in the guard delta.
|
| 813 |
+
input_checks: list[tuple[Any, object]] # list[tuple[InputTag, object]]
|
| 814 |
+
|
| 815 |
+
# Guards captured during the trace (delta + source-mapped).
|
| 816 |
+
# Each entry: (source, handler, expected_value, guard)
|
| 817 |
+
# handler is a pre-resolved GuardCheckSpec from GUARD_VALUE_DISPATCH.
|
| 818 |
+
guards: list[tuple[Source, GuardCheckSpec, object, Guard]]
|
| 819 |
+
|
| 820 |
+
# TreeSpec from pytree.tree_flatten of the (args, kwargs) structure.
|
| 821 |
+
# On cache hit, we verify the new call has the same treespec.
|
| 822 |
+
treespec: pytree.TreeSpec | None = None
|
| 823 |
+
|
| 824 |
+
# All sources accessed via VariableBuilder during the subgraph trace.
|
| 825 |
+
# On cache hit, we check if any modified VT's source is a base of one
|
| 826 |
+
# of these to detect mutations on captured variables.
|
| 827 |
+
traced_sources: OrderedSet[Source] = dataclasses.field(default_factory=OrderedSet)
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
class InvokeSubgraphCache(HopSubgraphCache):
|
| 831 |
+
def __init__(self) -> None:
|
| 832 |
+
self.autograd_cache: dict[str, Callable] = {}
|
| 833 |
+
self.proxy_dispatch_cache: dict[str, Callable] = {}
|
| 834 |
+
self.dynamo_installed_submodules: dict[CodeType, list[str]] = defaultdict(list)
|
| 835 |
+
self.lazy_bwd_cache: dict[
|
| 836 |
+
str, dict[tuple[object], tuple[torch.fx.GraphModule, int]]
|
| 837 |
+
] = defaultdict(dict)
|
| 838 |
+
self.effects_cache: dict[
|
| 839 |
+
str, set
|
| 840 |
+
] = {} # Maps identifier -> set of effect types
|
| 841 |
+
# fn.__code__ → list of (condition, cache_entry) pairs. Walked linearly
|
| 842 |
+
# on lookup; first matching condition wins.
|
| 843 |
+
self.subgraph_reuse_cache: dict[
|
| 844 |
+
CodeType,
|
| 845 |
+
list[tuple[InvokeSubgraphReuseCondition, InvokeSubgraphReuseEntry]],
|
| 846 |
+
] = defaultdict(list)
|
| 847 |
+
# fn_code → {hash_key → cache_entry}. Used by user-provided
|
| 848 |
+
# reuse_hash_fn for O(1) subgraph reuse lookup.
|
| 849 |
+
self.subgraph_reuse_key_cache: dict[
|
| 850 |
+
CodeType, dict[int, InvokeSubgraphReuseEntry]
|
| 851 |
+
] = defaultdict(dict)
|
| 852 |
+
|
| 853 |
+
def add_dynamo_installed_submodule(
|
| 854 |
+
self, fn_code: CodeType, identifier: str
|
| 855 |
+
) -> None:
|
| 856 |
+
self.dynamo_installed_submodules[fn_code].append(identifier)
|
| 857 |
+
|
| 858 |
+
def get_dynamo_installed_submodules(self, fn_code: CodeType) -> list[str]:
|
| 859 |
+
return self.dynamo_installed_submodules.get(fn_code, [])
|
| 860 |
+
|
| 861 |
+
def add_autograd_key_entry(self, identifier: str, key: Callable) -> None:
|
| 862 |
+
self.autograd_cache[identifier] = key
|
| 863 |
+
|
| 864 |
+
def get_autograd_key_entry(self, identifier: str) -> Callable | None:
|
| 865 |
+
return self.autograd_cache.get(identifier, None)
|
| 866 |
+
|
| 867 |
+
def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None:
|
| 868 |
+
self.proxy_dispatch_cache[identifier] = key
|
| 869 |
+
|
| 870 |
+
def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None:
|
| 871 |
+
return self.proxy_dispatch_cache.get(identifier, None)
|
| 872 |
+
|
| 873 |
+
def add_lazy_bwd_entry(
|
| 874 |
+
self,
|
| 875 |
+
identifier: str,
|
| 876 |
+
tangent_metadata: tuple[object],
|
| 877 |
+
gmod: torch.fx.GraphModule,
|
| 878 |
+
) -> int:
|
| 879 |
+
# Save the number of existing graph modules in the dictionary to get the suffix
|
| 880 |
+
num_gmods = len(self.lazy_bwd_cache[identifier])
|
| 881 |
+
self.lazy_bwd_cache[identifier][tangent_metadata] = (gmod, num_gmods)
|
| 882 |
+
return num_gmods
|
| 883 |
+
|
| 884 |
+
def get_lazy_bwd_entry(
|
| 885 |
+
self, identifier: str, tangent_metadata: tuple[object]
|
| 886 |
+
) -> tuple[torch.fx.GraphModule | None, int | None]:
|
| 887 |
+
if identifier not in self.lazy_bwd_cache:
|
| 888 |
+
return (None, None)
|
| 889 |
+
|
| 890 |
+
return self.lazy_bwd_cache[identifier].get(tangent_metadata, (None, None))
|
| 891 |
+
|
| 892 |
+
def add_effects(self, identifier: str, effects: set) -> None:
|
| 893 |
+
"""Store the effect types for a given invoke_subgraph identifier."""
|
| 894 |
+
if prev_effects := self.effects_cache.get(identifier, None):
|
| 895 |
+
if effects != prev_effects:
|
| 896 |
+
raise AssertionError(
|
| 897 |
+
"Different number of effects were found for invoke_subgraph "
|
| 898 |
+
f"call with identifier {identifier}. \n"
|
| 899 |
+
f"Previously we had the following effects: {prev_effects}.\n"
|
| 900 |
+
f"But now we have: {effects}."
|
| 901 |
+
)
|
| 902 |
+
self.effects_cache[identifier] = effects
|
| 903 |
+
|
| 904 |
+
def get_effects(self, identifier: str) -> set | None:
|
| 905 |
+
"""Retrieve the effect types for a given invoke_subgraph identifier."""
|
| 906 |
+
return self.effects_cache.get(identifier, None)
|
| 907 |
+
|
| 908 |
+
def add_reuse_entry(
|
| 909 |
+
self,
|
| 910 |
+
fn_code: CodeType,
|
| 911 |
+
condition: InvokeSubgraphReuseCondition,
|
| 912 |
+
entry: InvokeSubgraphReuseEntry,
|
| 913 |
+
max_reuse_entries: int = 8,
|
| 914 |
+
) -> None:
|
| 915 |
+
entries = self.subgraph_reuse_cache[fn_code]
|
| 916 |
+
if len(entries) >= max_reuse_entries:
|
| 917 |
+
raise RuntimeError(
|
| 918 |
+
f"invoke_subgraph: exceeded maximum reuse entries "
|
| 919 |
+
f"({max_reuse_entries}) for function code {fn_code}. "
|
| 920 |
+
f"This most likely means a guard keeps failing on every "
|
| 921 |
+
f"invocation, preventing subgraph reuse. "
|
| 922 |
+
f"Set TORCH_LOGS='+hierarchical_compile' to identify which "
|
| 923 |
+
f"guard is failing. If reuse is genuinely not possible and "
|
| 924 |
+
f"you need more cache entries, increase the limit via the "
|
| 925 |
+
f"max_reuse_entries argument to nested_compile_region()."
|
| 926 |
+
)
|
| 927 |
+
entries.append((condition, entry))
|
| 928 |
+
|
| 929 |
+
def find_reuse_entry(
|
| 930 |
+
self,
|
| 931 |
+
fn_code: CodeType,
|
| 932 |
+
evaluator: Callable[
|
| 933 |
+
[InvokeSubgraphReuseCondition, InvokeSubgraphReuseEntry], bool
|
| 934 |
+
],
|
| 935 |
+
) -> InvokeSubgraphReuseEntry | None:
|
| 936 |
+
entries = self.subgraph_reuse_cache.get(fn_code, [])
|
| 937 |
+
for i, (condition, entry) in enumerate(entries):
|
| 938 |
+
if evaluator(condition, entry):
|
| 939 |
+
# MRU: move the hit entry to the front for faster future lookups
|
| 940 |
+
if i > 0:
|
| 941 |
+
entries.insert(0, entries.pop(i))
|
| 942 |
+
return entry
|
| 943 |
+
return None
|
| 944 |
+
|
| 945 |
+
def find_reuse_entry_by_key(
|
| 946 |
+
self, fn_code: CodeType, hash_key: int
|
| 947 |
+
) -> InvokeSubgraphReuseEntry | None:
|
| 948 |
+
return self.subgraph_reuse_key_cache.get(fn_code, {}).get(hash_key)
|
| 949 |
+
|
| 950 |
+
def add_reuse_entry_by_key(
|
| 951 |
+
self,
|
| 952 |
+
fn_code: CodeType,
|
| 953 |
+
hash_key: int,
|
| 954 |
+
entry: InvokeSubgraphReuseEntry,
|
| 955 |
+
max_reuse_entries: int = 8,
|
| 956 |
+
) -> None:
|
| 957 |
+
key_cache = self.subgraph_reuse_key_cache[fn_code]
|
| 958 |
+
if len(key_cache) >= max_reuse_entries and hash_key not in key_cache:
|
| 959 |
+
raise RuntimeError(
|
| 960 |
+
f"invoke_subgraph: exceeded maximum reuse entries "
|
| 961 |
+
f"({max_reuse_entries}) for function code {fn_code} (hash-key path). "
|
| 962 |
+
f"Increase the limit via the max_reuse_entries argument to "
|
| 963 |
+
f"nested_compile_region()."
|
| 964 |
+
)
|
| 965 |
+
key_cache[hash_key] = entry
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
class HopDispatchSetCache:
|
| 969 |
+
def __init__(self) -> None:
|
| 970 |
+
# Delayed import to avoid circular dependency
|
| 971 |
+
from torch._higher_order_ops.invoke_subgraph import invoke_subgraph
|
| 972 |
+
|
| 973 |
+
self.hop_cache_map = {invoke_subgraph: InvokeSubgraphCache()}
|
| 974 |
+
|
| 975 |
+
def get_cache(self, op: torch._ops.HigherOrderOperator) -> HopSubgraphCache | None:
|
| 976 |
+
if op not in self.hop_cache_map:
|
| 977 |
+
return None
|
| 978 |
+
return self.hop_cache_map[op] # type: ignore[index]
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
_TLS = threading.local()
|
| 982 |
+
|
| 983 |
+
"""
|
| 984 |
+
TracingContext is the source of truth for all currently accumulated information
|
| 985 |
+
needed to trace. Its lifecycle is kept 1:1 when using TorchDynamo, but other systems
|
| 986 |
+
are open to managing their own TracingContext with that in mind.
|
| 987 |
+
|
| 988 |
+
The purpose of TracingContext is not to be a dumping ground, or god object, but rather to avoid
|
| 989 |
+
having to plumb complex subsystems across multiple verticals.
|
| 990 |
+
|
| 991 |
+
Ex: A common example is guard accumulation between dynamo, shape_env, aot_autograd, and inductor.
|
| 992 |
+
Accessing the current tracing context via
|
| 993 |
+
TracingContext.get() allows users to accumulate their own guards for processing, without needing to know how
|
| 994 |
+
to plumb objects back up to where frame interpretation happened.
|
| 995 |
+
|
| 996 |
+
Note that you can end up with multiple TracingContext for a single compilation
|
| 997 |
+
of a frame, as we reset the TracingContext whenever we restart analysis.
|
| 998 |
+
CompileContext is a more overarching context that encompasses multiple restarts.
|
| 999 |
+
"""
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
class CompileContext:
|
| 1003 |
+
@staticmethod
|
| 1004 |
+
def get() -> CompileContext:
|
| 1005 |
+
if _TLS.compile_context is None:
|
| 1006 |
+
raise AssertionError("compile_context is not set")
|
| 1007 |
+
return _TLS.compile_context
|
| 1008 |
+
|
| 1009 |
+
@staticmethod
|
| 1010 |
+
def try_get() -> CompileContext | None:
|
| 1011 |
+
return getattr(_TLS, "compile_context", None)
|
| 1012 |
+
|
| 1013 |
+
def __init__(self, compile_id: CompileId | None) -> None:
|
| 1014 |
+
if compile_id is not None and not isinstance(compile_id, CompileId):
|
| 1015 |
+
raise AssertionError(
|
| 1016 |
+
f"compile_id must be None or CompileId, got {type(compile_id)}"
|
| 1017 |
+
)
|
| 1018 |
+
self.compile_id: CompileId | None = compile_id
|
| 1019 |
+
self.attempt = 0
|
| 1020 |
+
# Verbose ShapeEnv guards produced.
|
| 1021 |
+
self.shape_env_guards: list[str] = []
|
| 1022 |
+
|
| 1023 |
+
@staticmethod
|
| 1024 |
+
def current_compile_id() -> CompileId | None:
|
| 1025 |
+
self = CompileContext.try_get()
|
| 1026 |
+
if self is None:
|
| 1027 |
+
return None
|
| 1028 |
+
return self.compile_id
|
| 1029 |
+
|
| 1030 |
+
@staticmethod
|
| 1031 |
+
def current_trace_id() -> TraceId | None:
|
| 1032 |
+
self = CompileContext.try_get()
|
| 1033 |
+
if self is None:
|
| 1034 |
+
return None
|
| 1035 |
+
if self.compile_id is None:
|
| 1036 |
+
return None
|
| 1037 |
+
return TraceId(self.compile_id, self.attempt)
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
@dataclass
|
| 1041 |
+
class InlinedCodeCache:
|
| 1042 |
+
"""Cache for code-object-derived data used during inlining."""
|
| 1043 |
+
|
| 1044 |
+
instructions: list[Any]
|
| 1045 |
+
indexof: dict[Any, int]
|
| 1046 |
+
code_options: dict[str, Any]
|
| 1047 |
+
|
| 1048 |
+
|
| 1049 |
+
class TracingContext:
|
| 1050 |
+
"""
|
| 1051 |
+
Provides the currently installed TracingContext, or None.
|
| 1052 |
+
|
| 1053 |
+
Note that it is a staticmethod, and invocations outside of `with tracing()` (see below), are valid but
|
| 1054 |
+
will return None.
|
| 1055 |
+
"""
|
| 1056 |
+
|
| 1057 |
+
@staticmethod
|
| 1058 |
+
def try_get() -> TracingContext | None:
|
| 1059 |
+
return getattr(_TLS, "tracing_context", None)
|
| 1060 |
+
|
| 1061 |
+
@staticmethod
|
| 1062 |
+
def get() -> TracingContext:
|
| 1063 |
+
if ctx := TracingContext.try_get():
|
| 1064 |
+
return ctx
|
| 1065 |
+
raise RuntimeError(
|
| 1066 |
+
"TracingContext.get() must be called within an ongoing trace."
|
| 1067 |
+
)
|
| 1068 |
+
|
| 1069 |
+
def __init__(self, fake_mode: FakeTensorMode | None) -> None:
|
| 1070 |
+
self.guards_context = GuardsContext()
|
| 1071 |
+
self.module_context = ModuleContext()
|
| 1072 |
+
self.global_context = GlobalContext()
|
| 1073 |
+
self.previously_inlined_functions: dict[Any, Any] = dict()
|
| 1074 |
+
self.previously_cleaned_instructions: dict[Any, Any] = dict()
|
| 1075 |
+
# Combined cache for inlined code data (instructions, indexof, code_options)
|
| 1076 |
+
self.inlined_code_cache: dict[Any, InlinedCodeCache] = dict()
|
| 1077 |
+
self.fake_mode: FakeTensorMode | None = fake_mode
|
| 1078 |
+
self.frame_summary_stack: list[traceback.FrameSummary] = []
|
| 1079 |
+
# This is morally part of frame_summary_stack, but it is kept separate
|
| 1080 |
+
# for clarity. As we process a frame, this variable gets updated
|
| 1081 |
+
# to keep track of what line we are in the function. We make a
|
| 1082 |
+
# function call, this gets cleared and the frame location is pushed
|
| 1083 |
+
# to frame_summary_stack (prepping this variable for the inner frame's
|
| 1084 |
+
# progress)
|
| 1085 |
+
self.loc_in_frame: tuple[str, int, str] | None = None
|
| 1086 |
+
# this is only set after aot_autograd
|
| 1087 |
+
self.fw_metadata: ViewAndMutationMeta | None = None
|
| 1088 |
+
# this is only set when the DDPOptimizer is used
|
| 1089 |
+
self.ddp_optimizer_ctx: DDPOptimizerContext | None = None
|
| 1090 |
+
# this is only set after aot_autograd
|
| 1091 |
+
self.aot_graph_name: list[str] | None = None
|
| 1092 |
+
self.params_flat: list[Any] | None = None
|
| 1093 |
+
self.params_flat_unwrap_subclasses: list[Any] | None = None
|
| 1094 |
+
self.params_unwrapped_to_flat_index: list[Any] | None = None
|
| 1095 |
+
# this is for extended return calling convention from backend
|
| 1096 |
+
# compiler to aot_autograd
|
| 1097 |
+
# Per output, what the compiler specified stride of the output is,
|
| 1098 |
+
# or None if no stride is known. This is always the HINT, it
|
| 1099 |
+
# is never a SymInt (it would be better if it was a SymInt, but
|
| 1100 |
+
# I can't conveniently get this from Inductor atm. Also, be
|
| 1101 |
+
# careful not to accidentally induce guards on the SymInt if
|
| 1102 |
+
# you ever do change this in aot_autograd.py; you should check
|
| 1103 |
+
# on permutations preferentially.)
|
| 1104 |
+
self.output_strides: list[tuple[int, ...] | None] | None = None
|
| 1105 |
+
# When this is True, whenever we encounter an int in Dynamo tracing,
|
| 1106 |
+
# we will (1) force unspec it and (2) force it as a size-like unbacked
|
| 1107 |
+
# integer. This is currently used when processing certain lists of
|
| 1108 |
+
# ints that are known to be size-like and may have 0/1 entries that we
|
| 1109 |
+
# must not specialize on.
|
| 1110 |
+
self.force_unspec_int_unbacked_size_like = False
|
| 1111 |
+
# See note [Tensor Fakification and Symbol Caching]
|
| 1112 |
+
self.tensor_to_context = WeakTensorKeyDictionary()
|
| 1113 |
+
|
| 1114 |
+
# If this true, Aot Autograd will return output Fake Tensors with appropriate
|
| 1115 |
+
# meta on the first invocation
|
| 1116 |
+
# see note: [Returning Fake Tensors on First AOT Autograd Call]
|
| 1117 |
+
self.fakify_first_call = False
|
| 1118 |
+
self.hop_dispatch_set_cache = HopDispatchSetCache()
|
| 1119 |
+
# list of code objects for inlined functions
|
| 1120 |
+
self.traced_code: list[CodeType] = []
|
| 1121 |
+
self.cudagraph_annotation: Any = None
|
| 1122 |
+
|
| 1123 |
+
def clear(self) -> None:
|
| 1124 |
+
# Look at the note in output_graph.py in function `save_global_state`
|
| 1125 |
+
# for the context on clearing global context.
|
| 1126 |
+
self.global_context.global_state = {}
|
| 1127 |
+
self.previously_inlined_functions.clear()
|
| 1128 |
+
self.previously_cleaned_instructions.clear()
|
| 1129 |
+
self.inlined_code_cache.clear()
|
| 1130 |
+
|
| 1131 |
+
@staticmethod
|
| 1132 |
+
@contextmanager
|
| 1133 |
+
def patch(**kwargs: Any) -> Generator[None, None, None]:
|
| 1134 |
+
prior = {}
|
| 1135 |
+
ctx = TracingContext.get()
|
| 1136 |
+
|
| 1137 |
+
for key in kwargs:
|
| 1138 |
+
# KeyError on invalid entry
|
| 1139 |
+
prior[key] = getattr(ctx, key)
|
| 1140 |
+
for key, val in kwargs.items():
|
| 1141 |
+
setattr(ctx, key, val)
|
| 1142 |
+
try:
|
| 1143 |
+
yield
|
| 1144 |
+
finally:
|
| 1145 |
+
for key, val in prior.items():
|
| 1146 |
+
setattr(ctx, key, val)
|
| 1147 |
+
|
| 1148 |
+
@staticmethod
|
| 1149 |
+
def extract_stack() -> traceback.StackSummary:
|
| 1150 |
+
self = TracingContext.try_get()
|
| 1151 |
+
if self is None:
|
| 1152 |
+
return traceback.StackSummary()
|
| 1153 |
+
stack = self.frame_summary_stack
|
| 1154 |
+
if self.loc_in_frame is not None:
|
| 1155 |
+
stack = stack + [self._populate_loc_in_frame_summary()]
|
| 1156 |
+
return traceback.StackSummary.from_list(stack)
|
| 1157 |
+
|
| 1158 |
+
def _populate_loc_in_frame_summary(self) -> traceback.FrameSummary:
|
| 1159 |
+
if self.loc_in_frame is None:
|
| 1160 |
+
raise AssertionError("loc_in_frame must not be None")
|
| 1161 |
+
filename, lineno, frame_name = self.loc_in_frame
|
| 1162 |
+
return traceback.FrameSummary(filename, lineno, frame_name, lookup_line=False)
|
| 1163 |
+
|
| 1164 |
+
# Call this when you want to call into some code that isn't necessarily
|
| 1165 |
+
# associated with the current frame state
|
| 1166 |
+
@staticmethod
|
| 1167 |
+
@contextlib.contextmanager
|
| 1168 |
+
def clear_frame() -> Generator[None, None, None]:
|
| 1169 |
+
tc = TracingContext.get()
|
| 1170 |
+
with (
|
| 1171 |
+
unittest.mock.patch.object(tc, "frame_summary_stack", []),
|
| 1172 |
+
unittest.mock.patch.object(tc, "loc_in_frame", None),
|
| 1173 |
+
):
|
| 1174 |
+
try:
|
| 1175 |
+
yield
|
| 1176 |
+
except Exception as e:
|
| 1177 |
+
# Prevent real_stack from getting attached
|
| 1178 |
+
#
|
| 1179 |
+
# The invariant is that if an Exception as real_stack, we've
|
| 1180 |
+
# appropriately attached a user stack and we no longer need to
|
| 1181 |
+
# attach anything. Because we cannot conveniently interpose
|
| 1182 |
+
# when an exception is thrown, we instead interpose everywhere
|
| 1183 |
+
# we set what the user stack is set (using the context
|
| 1184 |
+
# manager). However, our compiler stack does "tail calls"
|
| 1185 |
+
# (when it calls into user compiler), at which point the
|
| 1186 |
+
# parent exception frames would incorrectly attach an
|
| 1187 |
+
# incorrect frame.
|
| 1188 |
+
#
|
| 1189 |
+
# However, if, somehow, someone raised an exception with this
|
| 1190 |
+
# scope that had a stack (for example, because they are
|
| 1191 |
+
# restoring the user stack state appropriately as they process
|
| 1192 |
+
# node by node), we should respect it. Thus, we cannot
|
| 1193 |
+
# unconditionally set None.
|
| 1194 |
+
if not hasattr(e, "real_stack"):
|
| 1195 |
+
e.real_stack = None # type: ignore[attr-defined]
|
| 1196 |
+
raise
|
| 1197 |
+
|
| 1198 |
+
@staticmethod
|
| 1199 |
+
@contextlib.contextmanager
|
| 1200 |
+
def current_frame(
|
| 1201 |
+
frame_summary: traceback.FrameSummary | None,
|
| 1202 |
+
) -> Generator[None, None, None]:
|
| 1203 |
+
# frame_summary can be None to solely take advantage of real_stack
|
| 1204 |
+
# attachment to thrown exceptions
|
| 1205 |
+
tc = TracingContext.get()
|
| 1206 |
+
if frame_summary is not None:
|
| 1207 |
+
tc.frame_summary_stack.append(frame_summary)
|
| 1208 |
+
old = tc.loc_in_frame
|
| 1209 |
+
tc.loc_in_frame = None
|
| 1210 |
+
try:
|
| 1211 |
+
yield
|
| 1212 |
+
except Exception as e:
|
| 1213 |
+
if not hasattr(e, "real_stack"):
|
| 1214 |
+
e.real_stack = tc.extract_stack() # type: ignore[attr-defined]
|
| 1215 |
+
raise
|
| 1216 |
+
finally:
|
| 1217 |
+
if frame_summary is not None:
|
| 1218 |
+
tc.frame_summary_stack.pop()
|
| 1219 |
+
tc.loc_in_frame = old
|
| 1220 |
+
|
| 1221 |
+
@staticmethod
|
| 1222 |
+
@contextlib.contextmanager
|
| 1223 |
+
def report_output_strides() -> Generator[
|
| 1224 |
+
list[tuple[int, ...] | None] | None, None, None
|
| 1225 |
+
]:
|
| 1226 |
+
tc = TracingContext.try_get()
|
| 1227 |
+
if tc is None:
|
| 1228 |
+
yield None
|
| 1229 |
+
return
|
| 1230 |
+
old_output_strides = tc.output_strides
|
| 1231 |
+
tc.output_strides = []
|
| 1232 |
+
try:
|
| 1233 |
+
yield tc.output_strides
|
| 1234 |
+
finally:
|
| 1235 |
+
tc.output_strides = old_output_strides
|
| 1236 |
+
|
| 1237 |
+
@staticmethod
|
| 1238 |
+
def set_current_loc(filename: str, lineno: int, frame_name: str) -> None:
|
| 1239 |
+
# Save the current location in the frame. Lazily generate the
|
| 1240 |
+
# framesummary.
|
| 1241 |
+
TracingContext.get().loc_in_frame = (filename, lineno, frame_name)
|
| 1242 |
+
|
| 1243 |
+
@staticmethod
|
| 1244 |
+
def get_traced_code() -> list[CodeType] | None:
|
| 1245 |
+
tc = TracingContext.try_get()
|
| 1246 |
+
if tc is None:
|
| 1247 |
+
return None
|
| 1248 |
+
return tc.traced_code
|
| 1249 |
+
|
| 1250 |
+
|
| 1251 |
+
@contextmanager
|
| 1252 |
+
def compile_context(
|
| 1253 |
+
context: CompileContext | None,
|
| 1254 |
+
) -> Generator[CompileContext | None, None, None]:
|
| 1255 |
+
old_context = getattr(_TLS, "compile_context", None)
|
| 1256 |
+
_TLS.compile_context = context
|
| 1257 |
+
try:
|
| 1258 |
+
yield context
|
| 1259 |
+
finally:
|
| 1260 |
+
_TLS.compile_context = old_context
|
| 1261 |
+
|
| 1262 |
+
|
| 1263 |
+
@contextmanager
|
| 1264 |
+
def tracing(
|
| 1265 |
+
context: TracingContext | None,
|
| 1266 |
+
) -> Generator[TracingContext | None, None, None]:
|
| 1267 |
+
"""
|
| 1268 |
+
This function installs the passed in tracing context as a dynamic scoped
|
| 1269 |
+
global variable.
|
| 1270 |
+
|
| 1271 |
+
Calls to TracingContext.get() while not under a `with tracing()` context
|
| 1272 |
+
will return None.
|
| 1273 |
+
"""
|
| 1274 |
+
old_context = getattr(_TLS, "tracing_context", None)
|
| 1275 |
+
_TLS.tracing_context = context
|
| 1276 |
+
try:
|
| 1277 |
+
yield context
|
| 1278 |
+
except Exception as e:
|
| 1279 |
+
if not hasattr(e, "real_stack") and context is not None:
|
| 1280 |
+
e.real_stack = context.extract_stack() # type: ignore[attr-defined]
|
| 1281 |
+
raise
|
| 1282 |
+
finally:
|
| 1283 |
+
if (
|
| 1284 |
+
context is not None
|
| 1285 |
+
and context.fake_mode is not None
|
| 1286 |
+
and context.fake_mode.shape_env is not None
|
| 1287 |
+
):
|
| 1288 |
+
context.fake_mode.shape_env.cleanup()
|
| 1289 |
+
_TLS.tracing_context = old_context
|
| 1290 |
+
|
| 1291 |
+
|
| 1292 |
+
@overload
|
| 1293 |
+
def dataclass_with_cached_hash(cls: type[T], **kwargs: Any) -> type[T]: ...
|
| 1294 |
+
|
| 1295 |
+
|
| 1296 |
+
@overload
|
| 1297 |
+
def dataclass_with_cached_hash(
|
| 1298 |
+
cls: None = None, **kwargs: Any
|
| 1299 |
+
) -> Callable[[type[T]], type[T]]: ...
|
| 1300 |
+
|
| 1301 |
+
|
| 1302 |
+
@dataclass_transform()
|
| 1303 |
+
def dataclass_with_cached_hash(
|
| 1304 |
+
cls: type[T] | None = None, **kwargs: Any
|
| 1305 |
+
) -> type[T] | Callable[[type[T]], type[T]]:
|
| 1306 |
+
def wrap(cls_inner: type[T]) -> type[T]:
|
| 1307 |
+
new_cls = dataclasses.dataclass(cls_inner, **kwargs)
|
| 1308 |
+
old_hash = cls_inner.__hash__
|
| 1309 |
+
|
| 1310 |
+
def __hash__(self) -> int:
|
| 1311 |
+
if not hasattr(self, "_hash"):
|
| 1312 |
+
object.__setattr__(self, "_hash", old_hash(self))
|
| 1313 |
+
return self._hash
|
| 1314 |
+
|
| 1315 |
+
def __reduce__(self):
|
| 1316 |
+
# Exclude _hash from pickling to ensure deterministic cache keys.
|
| 1317 |
+
# The _hash is a cached value that can be nondeterministically computed
|
| 1318 |
+
# (e.g., based on id() of objects), so it should not affect pickling.
|
| 1319 |
+
fields = dataclasses.fields(self)
|
| 1320 |
+
field_values = tuple(getattr(self, f.name) for f in fields if f.init)
|
| 1321 |
+
return (self.__class__, field_values)
|
| 1322 |
+
|
| 1323 |
+
new_cls.__hash__ = __hash__
|
| 1324 |
+
new_cls.__reduce__ = __reduce__
|
| 1325 |
+
return new_cls # type: ignore[return-value]
|
| 1326 |
+
|
| 1327 |
+
if cls is None:
|
| 1328 |
+
return wrap
|
| 1329 |
+
|
| 1330 |
+
return wrap(cls)
|
| 1331 |
+
|
| 1332 |
+
|
| 1333 |
+
# Subclasses can be found in torch/_dynamo/source.py
|
| 1334 |
+
# TODO(voz): Consider a toplevel torch/_source.py
|
| 1335 |
+
@dataclass_with_cached_hash(frozen=True)
|
| 1336 |
+
class Source:
|
| 1337 |
+
def is_dict_key(self) -> bool:
|
| 1338 |
+
return False
|
| 1339 |
+
|
| 1340 |
+
def is_ephemeral(self) -> bool:
|
| 1341 |
+
return False
|
| 1342 |
+
|
| 1343 |
+
def reconstruct(self, codegen: PyCodegen) -> None:
|
| 1344 |
+
raise NotImplementedError
|
| 1345 |
+
|
| 1346 |
+
@functools.cached_property
|
| 1347 |
+
def guard_source(self) -> GuardSource:
|
| 1348 |
+
raise NotImplementedError
|
| 1349 |
+
|
| 1350 |
+
@property
|
| 1351 |
+
def _name_template(self) -> str:
|
| 1352 |
+
"""
|
| 1353 |
+
A template for the name of the source. Used to prevent code duplication between
|
| 1354 |
+
`name` and `get_value`.
|
| 1355 |
+
|
| 1356 |
+
For non-ChainedSources, `name` and `get_value` use the returned string directly.
|
| 1357 |
+
|
| 1358 |
+
For ChainedSources, `name` and `get_value` expect the return to be a format string
|
| 1359 |
+
with `{0}` present - `name` and `get_value` will apply different values to this function's
|
| 1360 |
+
returned format string.
|
| 1361 |
+
"""
|
| 1362 |
+
raise NotImplementedError
|
| 1363 |
+
|
| 1364 |
+
@functools.cached_property
|
| 1365 |
+
def name(self) -> str:
|
| 1366 |
+
return self._name_template
|
| 1367 |
+
|
| 1368 |
+
def get_value(
|
| 1369 |
+
self,
|
| 1370 |
+
globals: dict[str, Any],
|
| 1371 |
+
locals: dict[str, Any],
|
| 1372 |
+
cache: dict[Source, Any],
|
| 1373 |
+
) -> Any:
|
| 1374 |
+
if self in cache:
|
| 1375 |
+
return cache[self]
|
| 1376 |
+
value = eval(self._name_template, globals, locals)
|
| 1377 |
+
cache[self] = value
|
| 1378 |
+
return value
|
| 1379 |
+
|
| 1380 |
+
def make_guard(self, fn: Callable[..., Any]) -> Guard:
|
| 1381 |
+
if self.guard_source is GuardSource.CONSTANT:
|
| 1382 |
+
raise NotImplementedError
|
| 1383 |
+
return Guard(self, fn)
|
| 1384 |
+
|
| 1385 |
+
def is_specialized_nn_module(self) -> bool:
|
| 1386 |
+
return self.guard_source.is_specialized_nn_module()
|
| 1387 |
+
|
| 1388 |
+
def subguards_allowed(self) -> bool:
|
| 1389 |
+
"""True if you can guard on attributes of this"""
|
| 1390 |
+
return self.guard_source != GuardSource.SYNTHETIC_LOCAL
|
| 1391 |
+
|
| 1392 |
+
def clone(self, transform_fn: Callable[[Source], Source] | None = None) -> Source:
|
| 1393 |
+
# Frozen dataclass, so returning self is effectively a clone.
|
| 1394 |
+
# Subclasses with mutable state should override.
|
| 1395 |
+
if transform_fn is not None:
|
| 1396 |
+
return transform_fn(self)
|
| 1397 |
+
return self
|
| 1398 |
+
|
| 1399 |
+
|
| 1400 |
+
# Subclasses can be found in torch/_dynamo/source.py
|
| 1401 |
+
@dataclass_with_cached_hash(frozen=True)
|
| 1402 |
+
class ChainedSource(Source):
|
| 1403 |
+
base: Source
|
| 1404 |
+
|
| 1405 |
+
def is_dict_key(self) -> bool:
|
| 1406 |
+
# Recurse until you either hit a ConstDictKey or a Source
|
| 1407 |
+
return self.base.is_dict_key()
|
| 1408 |
+
|
| 1409 |
+
def is_ephemeral(self) -> bool:
|
| 1410 |
+
return self.base.is_ephemeral()
|
| 1411 |
+
|
| 1412 |
+
@functools.cached_property
|
| 1413 |
+
def guard_source(self) -> GuardSource:
|
| 1414 |
+
return self.base.guard_source
|
| 1415 |
+
|
| 1416 |
+
def get_base(self) -> Source:
|
| 1417 |
+
current: Source = self
|
| 1418 |
+
while isinstance(current, ChainedSource):
|
| 1419 |
+
current = current.base
|
| 1420 |
+
return current
|
| 1421 |
+
|
| 1422 |
+
@functools.cached_property
|
| 1423 |
+
def name(self) -> str:
|
| 1424 |
+
return self._name_template.format(self.base.name)
|
| 1425 |
+
|
| 1426 |
+
def get_value(
|
| 1427 |
+
self,
|
| 1428 |
+
globals: dict[str, Any],
|
| 1429 |
+
locals: dict[str, Any],
|
| 1430 |
+
cache: dict[Source, Any],
|
| 1431 |
+
) -> Any:
|
| 1432 |
+
if self in cache:
|
| 1433 |
+
return cache[self]
|
| 1434 |
+
tmpvar = "tmp"
|
| 1435 |
+
counter = 0
|
| 1436 |
+
while tmpvar in locals:
|
| 1437 |
+
tmpvar = f"tmp{counter}"
|
| 1438 |
+
counter += 1
|
| 1439 |
+
locals[tmpvar] = self.base.get_value(globals, locals, cache)
|
| 1440 |
+
value = eval(self._name_template.format(tmpvar), globals, locals)
|
| 1441 |
+
del locals[tmpvar]
|
| 1442 |
+
cache[self] = value
|
| 1443 |
+
return value
|
| 1444 |
+
|
| 1445 |
+
def clone(self, transform_fn: Callable[[Source], Source] | None = None) -> Source:
|
| 1446 |
+
cloned_fields: dict[str, Any] = {"base": self.base.clone(transform_fn)}
|
| 1447 |
+
for f in dataclasses.fields(self):
|
| 1448 |
+
if f.name == "base":
|
| 1449 |
+
continue
|
| 1450 |
+
val = getattr(self, f.name)
|
| 1451 |
+
if isinstance(val, Source):
|
| 1452 |
+
cloned_fields[f.name] = val.clone(transform_fn)
|
| 1453 |
+
result = dataclasses.replace(self, **cloned_fields)
|
| 1454 |
+
if transform_fn is not None:
|
| 1455 |
+
result = transform_fn(result)
|
| 1456 |
+
return result
|
| 1457 |
+
|
| 1458 |
+
|
| 1459 |
+
def detect_fake_mode(inputs: Any = None) -> FakeTensorMode | None:
|
| 1460 |
+
"""
|
| 1461 |
+
Attempts to "detect" what the current fake mode is. If there is one ambiently
|
| 1462 |
+
available from TracingContext, we preferentially use that. Otherwise, we
|
| 1463 |
+
heuristically detect the fake mode via the following sources, in order of
|
| 1464 |
+
priority:
|
| 1465 |
+
|
| 1466 |
+
- Currently active fake mode on stack
|
| 1467 |
+
- Fake mode associated with passed in tensors (inputs does not
|
| 1468 |
+
have to be flattened)
|
| 1469 |
+
"""
|
| 1470 |
+
from torch._subclasses.fake_tensor import (
|
| 1471 |
+
FakeTensor,
|
| 1472 |
+
FakeTensorMode,
|
| 1473 |
+
get_plain_tensors,
|
| 1474 |
+
)
|
| 1475 |
+
|
| 1476 |
+
# If TracingContext has a fake_mode, use it authoritatively.
|
| 1477 |
+
# This is the case when Dynamo is driving compilation - any fake tensors
|
| 1478 |
+
# from other modes in the inputs will be refakified by the caller.
|
| 1479 |
+
if context := TracingContext.try_get():
|
| 1480 |
+
fake_mode = context.fake_mode
|
| 1481 |
+
if fake_mode is not None:
|
| 1482 |
+
return fake_mode
|
| 1483 |
+
|
| 1484 |
+
fake_modes = []
|
| 1485 |
+
|
| 1486 |
+
from torch.utils._python_dispatch import _get_current_dispatch_mode_stack
|
| 1487 |
+
|
| 1488 |
+
for i, m in enumerate(reversed(_get_current_dispatch_mode_stack())):
|
| 1489 |
+
if isinstance(m, FakeTensorMode):
|
| 1490 |
+
fake_modes.append((m, "active fake mode", i))
|
| 1491 |
+
|
| 1492 |
+
flat_inputs = pytree.tree_leaves(inputs)
|
| 1493 |
+
for i, flat_input in enumerate(flat_inputs):
|
| 1494 |
+
if isinstance(flat_input, FakeTensor):
|
| 1495 |
+
fake_modes.append((flat_input.fake_mode, "fake tensor input", i))
|
| 1496 |
+
if is_traceable_wrapper_subclass(flat_input):
|
| 1497 |
+
out: list[torch.Tensor | int | torch.SymInt] = []
|
| 1498 |
+
get_plain_tensors(flat_input, out=out) # type: ignore[arg-type]
|
| 1499 |
+
fake_tensors: list[FakeTensor] = [
|
| 1500 |
+
x for x in out if isinstance(x, FakeTensor)
|
| 1501 |
+
]
|
| 1502 |
+
fake_modes.extend(
|
| 1503 |
+
[
|
| 1504 |
+
(tensor.fake_mode, f"subclass input {i}", ix)
|
| 1505 |
+
for ix, tensor in enumerate(fake_tensors)
|
| 1506 |
+
]
|
| 1507 |
+
)
|
| 1508 |
+
|
| 1509 |
+
if fake_modes:
|
| 1510 |
+
fake_mode, desc1, i1 = fake_modes[0]
|
| 1511 |
+
for m, desc2, i2 in fake_modes[1:]:
|
| 1512 |
+
if fake_mode is not m:
|
| 1513 |
+
raise AssertionError(
|
| 1514 |
+
f"fake mode ({fake_mode}) from {desc1} {i1} doesn't match mode ({m}) from {desc2} {i2}\n\n"
|
| 1515 |
+
f"fake mode from {desc1} {i1} allocated at:\n{fake_mode.stack}\n"
|
| 1516 |
+
f"fake mode from {desc2} {i2} allocated at:\n{m.stack}"
|
| 1517 |
+
)
|
| 1518 |
+
|
| 1519 |
+
return fake_mode
|
| 1520 |
+
else:
|
| 1521 |
+
return None
|
| 1522 |
+
|
| 1523 |
+
|
| 1524 |
+
def active_fake_mode() -> FakeTensorMode | None:
|
| 1525 |
+
"""
|
| 1526 |
+
Inspects the dispatch mode stack for an active fake mode and returns it.
|
| 1527 |
+
Returns None if no fake mode is active.
|
| 1528 |
+
"""
|
| 1529 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 1530 |
+
from torch.utils._python_dispatch import _get_current_dispatch_mode_stack
|
| 1531 |
+
|
| 1532 |
+
for _, m in enumerate(reversed(_get_current_dispatch_mode_stack())):
|
| 1533 |
+
if isinstance(m, FakeTensorMode):
|
| 1534 |
+
return m
|
| 1535 |
+
|
| 1536 |
+
return None
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/__init__.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch._higher_order_ops._invoke_quant import (
|
| 2 |
+
invoke_quant,
|
| 3 |
+
invoke_quant_packed,
|
| 4 |
+
InvokeQuant,
|
| 5 |
+
)
|
| 6 |
+
from torch._higher_order_ops.aoti_call_delegate import aoti_call_delegate
|
| 7 |
+
from torch._higher_order_ops.associative_scan import associative_scan
|
| 8 |
+
from torch._higher_order_ops.auto_functionalize import (
|
| 9 |
+
auto_functionalized,
|
| 10 |
+
auto_functionalized_v2,
|
| 11 |
+
)
|
| 12 |
+
from torch._higher_order_ops.base_hop import BaseHOP
|
| 13 |
+
from torch._higher_order_ops.cond import cond
|
| 14 |
+
from torch._higher_order_ops.effects import with_effects
|
| 15 |
+
from torch._higher_order_ops.executorch_call_delegate import executorch_call_delegate
|
| 16 |
+
from torch._higher_order_ops.flat_apply import flat_apply
|
| 17 |
+
from torch._higher_order_ops.flex_attention import (
|
| 18 |
+
flex_attention,
|
| 19 |
+
flex_attention_backward,
|
| 20 |
+
)
|
| 21 |
+
from torch._higher_order_ops.foreach_map import _foreach_map, foreach_map
|
| 22 |
+
from torch._higher_order_ops.hints_wrap import hints_wrapper
|
| 23 |
+
from torch._higher_order_ops.inline_asm_elementwise import inline_asm_elementwise
|
| 24 |
+
from torch._higher_order_ops.invoke_leaf_function import invoke_leaf_function
|
| 25 |
+
from torch._higher_order_ops.invoke_subgraph import invoke_subgraph
|
| 26 |
+
from torch._higher_order_ops.local_map import local_map_hop
|
| 27 |
+
from torch._higher_order_ops.map import map
|
| 28 |
+
from torch._higher_order_ops.out_dtype import out_dtype
|
| 29 |
+
from torch._higher_order_ops.print import print
|
| 30 |
+
from torch._higher_order_ops.run_const_graph import run_const_graph
|
| 31 |
+
from torch._higher_order_ops.scan import scan
|
| 32 |
+
from torch._higher_order_ops.strict_mode import strict_mode
|
| 33 |
+
from torch._higher_order_ops.torchbind import call_torchbind
|
| 34 |
+
from torch._higher_order_ops.while_loop import (
|
| 35 |
+
while_loop,
|
| 36 |
+
while_loop_stack_output_op as while_loop_stack_output,
|
| 37 |
+
)
|
| 38 |
+
from torch._higher_order_ops.wrap import (
|
| 39 |
+
dynamo_bypassing_wrapper,
|
| 40 |
+
inductor_compiled_code,
|
| 41 |
+
tag_activation_checkpoint,
|
| 42 |
+
wrap_activation_checkpoint,
|
| 43 |
+
wrap_with_autocast,
|
| 44 |
+
wrap_with_set_grad_enabled,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
__all__ = [
|
| 49 |
+
"cond",
|
| 50 |
+
"while_loop",
|
| 51 |
+
"invoke_subgraph",
|
| 52 |
+
"scan",
|
| 53 |
+
"map",
|
| 54 |
+
"flex_attention",
|
| 55 |
+
"flex_attention_backward",
|
| 56 |
+
"hints_wrapper",
|
| 57 |
+
"BaseHOP",
|
| 58 |
+
"flat_apply",
|
| 59 |
+
"foreach_map",
|
| 60 |
+
"_foreach_map",
|
| 61 |
+
"with_effects",
|
| 62 |
+
"tag_activation_checkpoint",
|
| 63 |
+
"auto_functionalized",
|
| 64 |
+
"auto_functionalized_v2",
|
| 65 |
+
"associative_scan",
|
| 66 |
+
"out_dtype",
|
| 67 |
+
"executorch_call_delegate",
|
| 68 |
+
"call_torchbind",
|
| 69 |
+
"run_const_graph",
|
| 70 |
+
"InvokeQuant",
|
| 71 |
+
"invoke_leaf_function",
|
| 72 |
+
"invoke_quant",
|
| 73 |
+
"invoke_quant_packed",
|
| 74 |
+
"wrap_with_set_grad_enabled",
|
| 75 |
+
"wrap_with_autocast",
|
| 76 |
+
"wrap_activation_checkpoint",
|
| 77 |
+
"dynamo_bypassing_wrapper",
|
| 78 |
+
"strict_mode",
|
| 79 |
+
"aoti_call_delegate",
|
| 80 |
+
"map",
|
| 81 |
+
"while_loop_stack_output",
|
| 82 |
+
"local_map_hop",
|
| 83 |
+
"print",
|
| 84 |
+
"inductor_compiled_code",
|
| 85 |
+
"inline_asm_elementwise",
|
| 86 |
+
]
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/_invoke_quant.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
# need to fix prim_hop_base type annotations first
|
| 3 |
+
|
| 4 |
+
import dataclasses
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch._higher_order_ops.base_hop import BaseHOP, FunctionWithNoFreeVars
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class InvokeQuantTracer(BaseHOP):
|
| 11 |
+
def __init__(self) -> None:
|
| 12 |
+
super().__init__("invoke_quant_packed")
|
| 13 |
+
|
| 14 |
+
def __call__(self, subgraph, *operands, scheme=None, quant_options=None):
|
| 15 |
+
subgraph = FunctionWithNoFreeVars(subgraph)
|
| 16 |
+
return super().__call__(
|
| 17 |
+
subgraph, *operands, scheme=scheme, quant_options=quant_options
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
invoke_quant_packed = InvokeQuantTracer()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class InvokeQuantUnpacked(BaseHOP):
|
| 25 |
+
def __init__(self) -> None:
|
| 26 |
+
super().__init__("invoke_quant")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
invoke_quant = InvokeQuantUnpacked()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclasses.dataclass(frozen=True, repr=True)
|
| 33 |
+
class InvokeQuant:
|
| 34 |
+
"""
|
| 35 |
+
Invoke a quantization function that will be preserved as a single operator. Preservation
|
| 36 |
+
as a single operator aids in pattern matching and custom lowerings.
|
| 37 |
+
|
| 38 |
+
The operation appears as:
|
| 39 |
+
torch.ops.higher_order.invoke_quant(subgraph, *args, scheme=scheme)
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
codegen_low_precision: Use observed subgraph dtypes for codegen instead of
|
| 43 |
+
upcasting to fp32. Can improve performance for prologue fusion but
|
| 44 |
+
requires careful testing of numerics.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
codegen_low_precision: bool = True
|
| 48 |
+
|
| 49 |
+
def __call__(
|
| 50 |
+
self,
|
| 51 |
+
*args,
|
| 52 |
+
scheme: str | None = None,
|
| 53 |
+
**kwargs,
|
| 54 |
+
):
|
| 55 |
+
if not torch.compiler.is_compiling():
|
| 56 |
+
return args[0](*args[1:], **kwargs)
|
| 57 |
+
|
| 58 |
+
if scheme is not None:
|
| 59 |
+
kwargs["scheme"] = scheme
|
| 60 |
+
|
| 61 |
+
return invoke_quant_packed(*args, **kwargs, quant_options=self) # type: ignore[call-arg]
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/aoti_call_delegate.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# This source code is licensed under the BSD-style license found in the
|
| 7 |
+
# LICENSE file in the root directory of this source tree.
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.utils._pytree as pytree
|
| 13 |
+
from torch._ops import HigherOrderOperator
|
| 14 |
+
from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
|
| 15 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 16 |
+
disable_proxy_modes_tracing,
|
| 17 |
+
ProxyTorchDispatchMode,
|
| 18 |
+
track_tensor_tree,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
AOTI_LOWERED_MODULE = "AOTInductorEPModule/AOTInductorRunnerWrapper"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class AOTICallDelegate(HigherOrderOperator):
|
| 26 |
+
"""aoti_call_delegate is a HOP for calling AOTInductor lowered submodule in ExportedProgram.
|
| 27 |
+
|
| 28 |
+
It has the following signature:
|
| 29 |
+
aoti_call_delegate(
|
| 30 |
+
lowered_module: Union[AOTInductorEPModule, AOTInductorRunnerWrapper]
|
| 31 |
+
original_gm:fx.GraphModule,
|
| 32 |
+
weight_args: List[Tensor],
|
| 33 |
+
input_args: List[Tensor],
|
| 34 |
+
) -> outputs: List[Tensor]
|
| 35 |
+
|
| 36 |
+
where,
|
| 37 |
+
- lowered_module is the AOTInductor lowered submodule, backed by compiled .so file, supporting real tensor inputs
|
| 38 |
+
- original_gm is the stateless version of the original GraphModule before lowering, allowing FakeTensor propagation
|
| 39 |
+
- weight_args is the list of weights in original GraphModule, including parameters and buffers
|
| 40 |
+
- input_args is the list of flatten inputs
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(self) -> None:
|
| 44 |
+
super().__init__("aoti_call_delegate")
|
| 45 |
+
|
| 46 |
+
def __call__(
|
| 47 |
+
self,
|
| 48 |
+
lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
|
| 49 |
+
original_gm: torch.fx.GraphModule,
|
| 50 |
+
weight_args: list[torch.Tensor],
|
| 51 |
+
input_args: list[torch.Tensor],
|
| 52 |
+
) -> list[torch.Tensor]:
|
| 53 |
+
# pyrefly: ignore [missing-attribute]
|
| 54 |
+
return super().__call__(lowered_module, original_gm, weight_args, input_args)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
aoti_call_delegate = AOTICallDelegate()
|
| 58 |
+
aoti_call_delegate.fallthrough(torch._C.DispatchKey.PythonDispatcher)
|
| 59 |
+
aoti_call_delegate.fallthrough(torch._C.DispatchKey.PythonTLSSnapshot)
|
| 60 |
+
aoti_call_delegate.fallthrough(torch._C.DispatchKey.ADInplaceOrView)
|
| 61 |
+
aoti_call_delegate.fallthrough(torch._C.DispatchKey.AutocastCPU)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@aoti_call_delegate.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd)
|
| 65 |
+
def call_delegate_cpu(
|
| 66 |
+
lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
|
| 67 |
+
original_gm: torch.fx.GraphModule,
|
| 68 |
+
weight_args: list[torch.Tensor],
|
| 69 |
+
input_args: list[torch.Tensor],
|
| 70 |
+
) -> list[torch.Tensor]:
|
| 71 |
+
# FX creates this immutable_dict/list concept. Get rid of this.
|
| 72 |
+
map_types: dict[type, type] = {
|
| 73 |
+
torch.fx.immutable_collections.immutable_dict: dict,
|
| 74 |
+
torch.fx.immutable_collections.immutable_list: list,
|
| 75 |
+
}
|
| 76 |
+
new_args = pytree.tree_map_only(
|
| 77 |
+
tuple(map_types.keys()),
|
| 78 |
+
lambda a: map_types[type(a)](a),
|
| 79 |
+
weight_args + input_args,
|
| 80 |
+
lambda a: isinstance(a, tuple(map_types.keys())),
|
| 81 |
+
)
|
| 82 |
+
has_fake_args = any(isinstance(arg, FakeTensor) for arg in new_args)
|
| 83 |
+
if has_fake_args:
|
| 84 |
+
# use stateless original_gm for tracing with fake tensors
|
| 85 |
+
fake_out = original_gm(*new_args)
|
| 86 |
+
return fake_out
|
| 87 |
+
else:
|
| 88 |
+
# use AOTI Runner for real tensors
|
| 89 |
+
new_input_args = new_args[len(weight_args) :]
|
| 90 |
+
if type(lowered_module).__name__ == "AOTInductorRunnerWrapper":
|
| 91 |
+
return lowered_module(*new_input_args) # type: ignore[misc]
|
| 92 |
+
elif type(lowered_module).__name__ == "AOTInductorEPModule":
|
| 93 |
+
return lowered_module(new_input_args) # type: ignore[misc]
|
| 94 |
+
else:
|
| 95 |
+
raise RuntimeError(
|
| 96 |
+
f"Unexpected lowered_module type: {type(lowered_module)}."
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def trace_aoti_call_delegate(
|
| 101 |
+
proxy_mode, func_overload, lowered_module, original_gm, weight_args, input_args
|
| 102 |
+
):
|
| 103 |
+
proxy_mode.tracer.root.register_module("lowered_module", lowered_module)
|
| 104 |
+
proxy_mode.tracer.root.register_module("original_gm", original_gm)
|
| 105 |
+
|
| 106 |
+
node_args = (lowered_module, original_gm, weight_args, input_args)
|
| 107 |
+
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
|
| 108 |
+
|
| 109 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 110 |
+
"call_function", func_overload, proxy_args, {}, name="aoti_call_delegate"
|
| 111 |
+
)
|
| 112 |
+
with disable_proxy_modes_tracing():
|
| 113 |
+
out = call_delegate_cpu(lowered_module, original_gm, weight_args, input_args)
|
| 114 |
+
|
| 115 |
+
return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@aoti_call_delegate.py_impl(ProxyTorchDispatchMode)
|
| 119 |
+
def call_delegate_proxy_torch_dispatch_mode(
|
| 120 |
+
mode: ProxyTorchDispatchMode,
|
| 121 |
+
lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
|
| 122 |
+
original_gm: torch.fx.GraphModule,
|
| 123 |
+
weight_args: list[torch.Tensor],
|
| 124 |
+
input_args: list[torch.Tensor],
|
| 125 |
+
):
|
| 126 |
+
res = trace_aoti_call_delegate(
|
| 127 |
+
mode, aoti_call_delegate, lowered_module, original_gm, weight_args, input_args
|
| 128 |
+
)
|
| 129 |
+
return res
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@aoti_call_delegate.py_impl(FakeTensorMode)
|
| 133 |
+
def call_delegate_fake_tensor_mode(
|
| 134 |
+
mode: FakeTensorMode,
|
| 135 |
+
lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
|
| 136 |
+
original_gm: torch.fx.GraphModule,
|
| 137 |
+
weight_args: list[torch.Tensor],
|
| 138 |
+
input_args: list[torch.Tensor],
|
| 139 |
+
) -> list[torch.Tensor]:
|
| 140 |
+
with mode:
|
| 141 |
+
return call_delegate_cpu(lowered_module, original_gm, weight_args, input_args)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@aoti_call_delegate.py_functionalize_impl
|
| 145 |
+
def call_delegate_functionalize(
|
| 146 |
+
ctx,
|
| 147 |
+
lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
|
| 148 |
+
original_gm: torch.fx.GraphModule,
|
| 149 |
+
weight_args: list[torch.Tensor],
|
| 150 |
+
input_args: list[torch.Tensor],
|
| 151 |
+
):
|
| 152 |
+
unwrapped_weight_args = tuple(
|
| 153 |
+
ctx.unwrap_tensors(weight_arg) for weight_arg in weight_args
|
| 154 |
+
)
|
| 155 |
+
unwrapped_input_args = tuple(
|
| 156 |
+
ctx.unwrap_tensors(input_arg) for input_arg in input_args
|
| 157 |
+
)
|
| 158 |
+
with ctx.redispatch_to_next():
|
| 159 |
+
res = aoti_call_delegate(
|
| 160 |
+
lowered_module,
|
| 161 |
+
original_gm,
|
| 162 |
+
unwrapped_weight_args, # type: ignore[arg-type]
|
| 163 |
+
unwrapped_input_args, # type: ignore[arg-type]
|
| 164 |
+
)
|
| 165 |
+
return ctx.wrap_tensors(res)
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
import itertools
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch._prims_common as utils
|
| 9 |
+
import torch.utils._pytree as pytree
|
| 10 |
+
from torch._C import DispatchKey
|
| 11 |
+
from torch._higher_order_ops.utils import (
|
| 12 |
+
_maybe_compile_and_run_fn,
|
| 13 |
+
_maybe_run_with_interpreter,
|
| 14 |
+
check_input_alias_and_mutation_return_outputs,
|
| 15 |
+
check_meta_consistency,
|
| 16 |
+
create_bw_fn,
|
| 17 |
+
first_slice_copy,
|
| 18 |
+
first_slice_copy_with_grad,
|
| 19 |
+
materialize_as_graph,
|
| 20 |
+
reenter_make_fx,
|
| 21 |
+
save_values_for_backward,
|
| 22 |
+
saved_values,
|
| 23 |
+
split_into_chunks,
|
| 24 |
+
unique_graph_id,
|
| 25 |
+
validate_subgraph_args_types,
|
| 26 |
+
)
|
| 27 |
+
from torch._ops import HigherOrderOperator
|
| 28 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 29 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 30 |
+
disable_proxy_modes_tracing,
|
| 31 |
+
ProxyTorchDispatchMode,
|
| 32 |
+
track_tensor_tree,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
aten = torch._ops.ops.aten
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def wrap_combine_fn_flat(*args, combine_fn, spec, num_leaves):
|
| 40 |
+
if len(args) != 2 * num_leaves:
|
| 41 |
+
raise AssertionError(
|
| 42 |
+
f"Combine_fn received wrong number of arguments, expected {2 * num_leaves}, but got {len(args)}"
|
| 43 |
+
)
|
| 44 |
+
lhs = pytree.tree_unflatten(args[:num_leaves], spec)
|
| 45 |
+
rhs = pytree.tree_unflatten(args[num_leaves:], spec)
|
| 46 |
+
return combine_fn(lhs, rhs)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _interleave(a, b, dim=0):
|
| 50 |
+
# https://stackoverflow.com/questions/60869537/how-can-i-interleave-5-pytorch-tensors
|
| 51 |
+
if b_trunc := (a.shape[dim] == b.shape[dim] + 1):
|
| 52 |
+
pad = (
|
| 53 |
+
[0] * ((b.ndim - dim - 1) * 2 + 1)
|
| 54 |
+
+ [1]
|
| 55 |
+
+ [0] * (b.ndim * 2 - ((b.ndim - dim - 1) * 2 + 2))
|
| 56 |
+
)
|
| 57 |
+
b = torch.nn.functional.pad(b, pad)
|
| 58 |
+
|
| 59 |
+
stacked = torch.stack([a, b], dim=dim + 1)
|
| 60 |
+
interleaved = torch.flatten(stacked, start_dim=dim, end_dim=dim + 1)
|
| 61 |
+
# pyrefly: ignore [unbound-name]
|
| 62 |
+
if b_trunc:
|
| 63 |
+
# TODO: find torch alternative for slice_along dim for torch.jit.script to work
|
| 64 |
+
interleaved = aten.slice(interleaved, dim, 0, b.shape[dim] + a.shape[dim] - 1)
|
| 65 |
+
return interleaved
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def safe_map(f, *args):
|
| 69 |
+
args = list(map(list, args))
|
| 70 |
+
n = len(args[0])
|
| 71 |
+
for arg in args[1:]:
|
| 72 |
+
if len(arg) != n:
|
| 73 |
+
raise ValueError("length mismatch: {list(map(len, args))}")
|
| 74 |
+
|
| 75 |
+
def nf(a):
|
| 76 |
+
return f(*a)
|
| 77 |
+
|
| 78 |
+
return list(map(nf, zip(*args)))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class AssociativeScanOp(HigherOrderOperator):
|
| 82 |
+
def __init__(self):
|
| 83 |
+
super().__init__("associative_scan")
|
| 84 |
+
|
| 85 |
+
def __call__(self, combine_fn, xs, additional_inputs):
|
| 86 |
+
# There is currently an issue that the ScanOp is sometimes called with
|
| 87 |
+
# the additional_inputs being a list. See https://github.com/pytorch/pytorch/issues/145785
|
| 88 |
+
# Once this issue is resolved, the assertion should only allow tuples
|
| 89 |
+
# and the tuple cast should be removed
|
| 90 |
+
if not isinstance(additional_inputs, (tuple, list)):
|
| 91 |
+
raise AssertionError(
|
| 92 |
+
f"additional_inputs must be a tuple or list, got {type(additional_inputs)}"
|
| 93 |
+
)
|
| 94 |
+
additional_inputs = (
|
| 95 |
+
tuple(additional_inputs)
|
| 96 |
+
if isinstance(additional_inputs, list)
|
| 97 |
+
else additional_inputs
|
| 98 |
+
)
|
| 99 |
+
validate_subgraph_args_types(additional_inputs)
|
| 100 |
+
# pyrefly: ignore [missing-attribute]
|
| 101 |
+
return super().__call__(combine_fn, xs, additional_inputs)
|
| 102 |
+
|
| 103 |
+
# pyrefly: ignore [bad-override]
|
| 104 |
+
def gen_schema(self, combine_fn, xs, additional_inputs):
|
| 105 |
+
from torch._higher_order_ops.schema import HopSchemaGenerator
|
| 106 |
+
from torch._higher_order_ops.utils import materialize_as_graph
|
| 107 |
+
|
| 108 |
+
# For associative scan, we need two copies of xs for the combine function
|
| 109 |
+
# The combine function takes two elements and returns one element
|
| 110 |
+
xs_slice1 = [first_slice_copy(x) for x in xs]
|
| 111 |
+
xs_slice2 = [first_slice_copy(x) for x in xs]
|
| 112 |
+
all_inputs = tuple(xs_slice1 + xs_slice2 + list(additional_inputs))
|
| 113 |
+
|
| 114 |
+
combine_gm: torch.fx.GraphModule = materialize_as_graph(combine_fn, all_inputs)
|
| 115 |
+
(
|
| 116 |
+
_,
|
| 117 |
+
_,
|
| 118 |
+
_,
|
| 119 |
+
mutated_inputs,
|
| 120 |
+
outputs,
|
| 121 |
+
) = check_input_alias_and_mutation_return_outputs(combine_gm)
|
| 122 |
+
if len(mutated_inputs) > 0:
|
| 123 |
+
raise RuntimeError(
|
| 124 |
+
"For associative_scan, combine_fn cannot have in-place mutations but found "
|
| 125 |
+
f"{mutated_inputs}-th inputs are mutated."
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
schema_gen = HopSchemaGenerator(self)
|
| 129 |
+
schema_gen.add_arg("combine_fn", combine_gm)
|
| 130 |
+
|
| 131 |
+
for idx, x in enumerate(xs):
|
| 132 |
+
schema_gen.add_arg(f"xs{idx}", x)
|
| 133 |
+
|
| 134 |
+
for idx, arg in enumerate(additional_inputs):
|
| 135 |
+
schema_gen.add_arg(
|
| 136 |
+
f"additional_input{idx}",
|
| 137 |
+
arg,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
for out in outputs:
|
| 141 |
+
schema_gen.add_output(out)
|
| 142 |
+
|
| 143 |
+
schema_gen.add_schema_tree_spec(combine_fn, xs, additional_inputs)
|
| 144 |
+
return schema_gen.gen_schema()
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
associative_scan_op = AssociativeScanOp()
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def associative_scan(
|
| 151 |
+
combine_fn: Callable[[pytree.PyTree, pytree.PyTree], pytree.PyTree],
|
| 152 |
+
xs: pytree.PyTree,
|
| 153 |
+
dim: int,
|
| 154 |
+
reverse: bool = False,
|
| 155 |
+
combine_mode: str = "pointwise",
|
| 156 |
+
) -> torch.Tensor:
|
| 157 |
+
r"""
|
| 158 |
+
Performs an inclusive scan with an associative combine function.
|
| 159 |
+
|
| 160 |
+
.. warning::
|
| 161 |
+
|
| 162 |
+
``torch.associative_scan`` is a prototype feature in PyTorch. It currently
|
| 163 |
+
does not support autograd and you may run into miscompiles.
|
| 164 |
+
Read more about feature classification at:
|
| 165 |
+
https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
|
| 166 |
+
|
| 167 |
+
This operator requires runtime code generation and so requires support for
|
| 168 |
+
``torch.compile``. Further, only CUDA device codegen is supported at the moment.
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
combine_fn (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``,
|
| 172 |
+
or if input is a pytree ``(pytree, pytree) -> pytree``.
|
| 173 |
+
This function must be pure, i.e., no lifted arguments are supported at the moment,
|
| 174 |
+
satisfy the associative property and have no side-effects.
|
| 175 |
+
xs (torch.Tensor): The input tensor, or nested pytree of tensors.
|
| 176 |
+
All inputs are expected to have the same shape.
|
| 177 |
+
dim (int): the dimension to scan over
|
| 178 |
+
reverse (bool): A boolean stating if the scan should be reversed with respect to ``dim``, default ``False``.
|
| 179 |
+
combine_mode (str): A string indicating whether the ``combine_fn`` is ``pointwise`` or ``generic``, default ``pointwise``.
|
| 180 |
+
If ``combine_mode=pointwise``, ``combine_fn`` must be pure, may only contain pointwise operations
|
| 181 |
+
and ``xs`` must be CUDA tensors.
|
| 182 |
+
In all other cases ``combine_mode=generic`` should be used.
|
| 183 |
+
Note: ``combine_mode=pointwise`` is more efficient than ``combine_mode=generic``.
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
Example::
|
| 187 |
+
|
| 188 |
+
def add(x: torch.Tensor, y: torch.Tensor):
|
| 189 |
+
return x + y
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
cumsum = associative_scan(add, x, dim)
|
| 193 |
+
|
| 194 |
+
"""
|
| 195 |
+
# TODO: Support lifted arguments in inductor for associative_scan
|
| 196 |
+
# TODO: Support autograd for cases with lifted arguments for combine_mode=pointwise
|
| 197 |
+
|
| 198 |
+
# The reason we flatten xs before calling into dynamo is that
|
| 199 |
+
# we want to create a consistent input ordering for combine_fn
|
| 200 |
+
# and we also want to the input ordering matches the output ordering.
|
| 201 |
+
leaves_xs_orig, spec_xs = pytree.tree_flatten(xs)
|
| 202 |
+
|
| 203 |
+
def _validate_input(cfn, lxs, d, r, cm):
|
| 204 |
+
# Basic arguments check
|
| 205 |
+
if not callable(cfn):
|
| 206 |
+
raise ValueError(f"Combine_fn must be a callable, but got {cfn}")
|
| 207 |
+
if not isinstance(d, int):
|
| 208 |
+
raise ValueError("Dim must be an int, but got " + str(type(d)))
|
| 209 |
+
if not isinstance(r, bool):
|
| 210 |
+
raise RuntimeError("Reverse must be a bool, but got " + str(type(r)))
|
| 211 |
+
if cm not in ["pointwise", "generic"]:
|
| 212 |
+
raise ValueError(
|
| 213 |
+
f"Combine_mode must either 'pointwise' or 'generic', but got {cm}"
|
| 214 |
+
)
|
| 215 |
+
if cm == "pointwise" and not all(l.device.type in ("cuda", "xpu") for l in lxs):
|
| 216 |
+
raise ValueError(
|
| 217 |
+
"For combine_mode='pointwise', all input tensors need to be on CUDA or XPU"
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
# Checks for xs
|
| 221 |
+
if len(lxs) == 0:
|
| 222 |
+
raise ValueError("Expected at least 1 xs leaf")
|
| 223 |
+
if any(not isinstance(x, torch.Tensor) for x in lxs):
|
| 224 |
+
raise ValueError("xs leaves must be a Tensor")
|
| 225 |
+
if any(x.is_sparse for x in lxs):
|
| 226 |
+
raise ValueError(
|
| 227 |
+
"xs leaves must dense Tensors, consider using `to_dense()`"
|
| 228 |
+
)
|
| 229 |
+
if any(x.ndim <= d for x in lxs):
|
| 230 |
+
raise ValueError(
|
| 231 |
+
"All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0"
|
| 232 |
+
)
|
| 233 |
+
if any(x.shape[d] == 0 for x in lxs):
|
| 234 |
+
raise ValueError(
|
| 235 |
+
"All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0"
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
ndim = leaves_xs_orig[0].ndim
|
| 239 |
+
dim = utils.canonicalize_dim(ndim, dim)
|
| 240 |
+
|
| 241 |
+
_validate_input(combine_fn, leaves_xs_orig, dim, reverse, combine_mode)
|
| 242 |
+
|
| 243 |
+
# Move scan dim to 0 and always perform scan on dim 0
|
| 244 |
+
leaves_xs = [torch.movedim(elem, dim, 0) for elem in leaves_xs_orig]
|
| 245 |
+
|
| 246 |
+
if reverse:
|
| 247 |
+
leaves_xs = [torch.flip(elem, [0]) for elem in leaves_xs]
|
| 248 |
+
|
| 249 |
+
if combine_mode == "generic":
|
| 250 |
+
# The generic_associative_scan implementation calls the combine_fn with a `batch` along the scan dimension
|
| 251 |
+
# For example, consider:
|
| 252 |
+
# def add(x: torch.Tensor, y: torch.Tensor):
|
| 253 |
+
# return x + y
|
| 254 |
+
# leaves = torch.tensor([[0.0, 1.0, 2.0, 3.0]
|
| 255 |
+
# [0.0, 1.0, 2.0, 3.0]])
|
| 256 |
+
# which has shape 2 x 4;
|
| 257 |
+
# dim = 1;
|
| 258 |
+
# In the first iteration of `_scan` the combine_fn gets invoked with
|
| 259 |
+
# combine_fn([torch.tensor([[0.0, 2.0],
|
| 260 |
+
# [0.0, 2.0]])],
|
| 261 |
+
# [torch.tensor([[1.0, 3.0],
|
| 262 |
+
# [1.0, 3.0]])])
|
| 263 |
+
# The arguments are of shape 2 x 2, but can be evaluated in parallel along the scan dimension.
|
| 264 |
+
combine_fn = functools.partial(
|
| 265 |
+
wrap_combine_fn_flat,
|
| 266 |
+
combine_fn=torch.vmap(
|
| 267 |
+
combine_fn,
|
| 268 |
+
in_dims=(
|
| 269 |
+
pytree.tree_unflatten([0] * len(leaves_xs), spec_xs),
|
| 270 |
+
pytree.tree_unflatten([0] * len(leaves_xs), spec_xs),
|
| 271 |
+
),
|
| 272 |
+
out_dims=0,
|
| 273 |
+
),
|
| 274 |
+
spec=spec_xs,
|
| 275 |
+
num_leaves=len(leaves_xs),
|
| 276 |
+
)
|
| 277 |
+
out = generic_associative_scan(combine_fn, leaves_xs, additional_inputs=())
|
| 278 |
+
out = pytree.tree_unflatten(out, spec_xs)
|
| 279 |
+
else:
|
| 280 |
+
combine_fn = functools.partial(
|
| 281 |
+
wrap_combine_fn_flat,
|
| 282 |
+
combine_fn=combine_fn,
|
| 283 |
+
spec=spec_xs,
|
| 284 |
+
num_leaves=len(leaves_xs),
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
def run_flattened_associative_scan(combine_fn, leaves_xs):
|
| 288 |
+
return associative_scan_op(combine_fn, leaves_xs, additional_inputs=())
|
| 289 |
+
|
| 290 |
+
out = _maybe_compile_and_run_fn(
|
| 291 |
+
run_flattened_associative_scan,
|
| 292 |
+
combine_fn,
|
| 293 |
+
leaves_xs,
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
if reverse:
|
| 297 |
+
out = pytree.tree_map(lambda elem: elem.flip([0]), out)
|
| 298 |
+
|
| 299 |
+
out = pytree.tree_map(lambda elem: torch.movedim(elem, 0, dim), out)
|
| 300 |
+
|
| 301 |
+
return out
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def generic_associative_scan(operator, leaves, dim=0, additional_inputs=()):
|
| 305 |
+
r"""
|
| 306 |
+
This function performs the associative_scan operation.
|
| 307 |
+
The algorithm works by recursively collecting neighbours of ``leaves`` and subsequently
|
| 308 |
+
applying the ``operator`` on all pairs in parallel along ``dim``.
|
| 309 |
+
The results of the recursive calls are later combined.
|
| 310 |
+
|
| 311 |
+
Args:
|
| 312 |
+
operator (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``,
|
| 313 |
+
or if input is a pytree ``(pytree, pytree) -> pytree``.
|
| 314 |
+
This function must be pure, pointwise, and satisfy the associative property.
|
| 315 |
+
leaves (torch.Tensor): A list of torch.Tensors converted from the pytree of
|
| 316 |
+
``xs`` provided to ``associative_scan``.
|
| 317 |
+
All inputs are expected to have the same shape.
|
| 318 |
+
dim (int): the dimension to scan over
|
| 319 |
+
additional_inputs (Tuple of tensors): A tuple of lifted parameters from the global scope.
|
| 320 |
+
This parameter will be populated internally.
|
| 321 |
+
|
| 322 |
+
Example::
|
| 323 |
+
|
| 324 |
+
def add(x: torch.Tensor, y: torch.Tensor):
|
| 325 |
+
return x + y
|
| 326 |
+
|
| 327 |
+
leaves = torch.tensor([0.0, 1.0, 2.0, 3.0])
|
| 328 |
+
|
| 329 |
+
First iteration of _scan ->
|
| 330 |
+
# odd_elems -> apply operator on all neighbours
|
| 331 |
+
# odd_elems = operator([torch.tensor([0.0, 2.0])],
|
| 332 |
+
# [torch.tensor([1.0, 3.0])])
|
| 333 |
+
odd_elems = torch.tensor([1.0, 5.0])
|
| 334 |
+
Second iteration of _scan ->
|
| 335 |
+
# odd_elems = operator([torch.tensor([1.0])],
|
| 336 |
+
# [torch.tensor([5.0])])
|
| 337 |
+
odd_elems = torch.tensor([6.0])
|
| 338 |
+
# even_elems -> apply operator on all odd_elems and
|
| 339 |
+
# every second element of ``elems``, starting from the second element.
|
| 340 |
+
# even_elems is expanded with the first element of ``elems``
|
| 341 |
+
even_elems = [1.0]
|
| 342 |
+
# Merges odd_elems and even_elems
|
| 343 |
+
res = torch.tensor([1.0, 6.0])
|
| 344 |
+
# even_elems -> apply operator on all odd_elems and
|
| 345 |
+
# every second element of ``elems``, starting from the second element.
|
| 346 |
+
# even_elems is expanded with the first element of ``elems``
|
| 347 |
+
even_elems = [0.0, 3.0]
|
| 348 |
+
# Merges odd_elems and even_elems
|
| 349 |
+
res = torch.tensor([0.0, 1.0, 3.0, 6.0])
|
| 350 |
+
|
| 351 |
+
"""
|
| 352 |
+
|
| 353 |
+
def call_operator(*args):
|
| 354 |
+
return pytree.tree_leaves(operator(*args))
|
| 355 |
+
|
| 356 |
+
def _scan(elems):
|
| 357 |
+
"""Perform the actual recursive scan on ``elems``."""
|
| 358 |
+
num_elems = elems[0].shape[dim]
|
| 359 |
+
|
| 360 |
+
if num_elems < 2:
|
| 361 |
+
return elems
|
| 362 |
+
|
| 363 |
+
reduced_elems = call_operator(
|
| 364 |
+
*[aten.slice(elem, dim, 0, -1, 2) for elem in elems],
|
| 365 |
+
*[aten.slice(elem, dim, 1, None, 2) for elem in elems],
|
| 366 |
+
*additional_inputs,
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
# Recursively compute scan for partially reduced tensors.
|
| 370 |
+
odd_elems = _scan(reduced_elems)
|
| 371 |
+
|
| 372 |
+
if num_elems % 2 == 0:
|
| 373 |
+
even_elems = call_operator(
|
| 374 |
+
*[aten.slice(e, dim, 0, -1) for e in odd_elems],
|
| 375 |
+
*[aten.slice(e, dim, 2, None, 2) for e in elems],
|
| 376 |
+
*additional_inputs,
|
| 377 |
+
)
|
| 378 |
+
else:
|
| 379 |
+
even_elems = call_operator(
|
| 380 |
+
*odd_elems,
|
| 381 |
+
*[aten.slice(e, dim, 2, None, 2) for e in elems],
|
| 382 |
+
*additional_inputs,
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
# The first element of a scan is the same as the first element
|
| 386 |
+
# of the original `elems`.
|
| 387 |
+
even_elems = [
|
| 388 |
+
torch.cat([aten.slice(elem, dim, 0, 1), result], dim=dim)
|
| 389 |
+
if result.shape.numel() > 0 and elem.shape[dim] > 0
|
| 390 |
+
else result
|
| 391 |
+
if result.shape.numel() > 0
|
| 392 |
+
else aten.slice(
|
| 393 |
+
elem, dim, 0, 1
|
| 394 |
+
) # Jax allows/ignores concat with 0-dim, Pytorch does not
|
| 395 |
+
for (elem, result) in zip(elems, even_elems)
|
| 396 |
+
]
|
| 397 |
+
|
| 398 |
+
return list(
|
| 399 |
+
safe_map(functools.partial(_interleave, dim=dim), even_elems, odd_elems)
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
scans = _scan(leaves)
|
| 403 |
+
|
| 404 |
+
return scans
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def trace_associative_scan(
|
| 408 |
+
proxy_mode,
|
| 409 |
+
func_overload,
|
| 410 |
+
combine_fn: Callable,
|
| 411 |
+
xs: list[torch.Tensor],
|
| 412 |
+
additional_inputs: tuple[torch.Tensor],
|
| 413 |
+
):
|
| 414 |
+
from torch._dynamo.utils import clone_input
|
| 415 |
+
|
| 416 |
+
with disable_proxy_modes_tracing():
|
| 417 |
+
sample_xs = [first_slice_copy(x) for x in itertools.chain(xs, xs)]
|
| 418 |
+
sample_additional_inputs = [
|
| 419 |
+
clone_input(x) if isinstance(x, torch.Tensor) else x
|
| 420 |
+
for x in additional_inputs
|
| 421 |
+
]
|
| 422 |
+
combine_graph = reenter_make_fx(combine_fn)(
|
| 423 |
+
*sample_xs, *sample_additional_inputs
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
outputs = None
|
| 427 |
+
for node in combine_graph.graph.nodes:
|
| 428 |
+
if node.op == "output":
|
| 429 |
+
if outputs is not None:
|
| 430 |
+
raise AssertionError("found multiple output nodes in combine_graph")
|
| 431 |
+
if len(node.args) != 1:
|
| 432 |
+
raise AssertionError(
|
| 433 |
+
f"expected output node to have 1 arg, got {len(node.args)}"
|
| 434 |
+
)
|
| 435 |
+
outputs = node.args[0]
|
| 436 |
+
|
| 437 |
+
if outputs is None:
|
| 438 |
+
raise AssertionError("no output node found in combine_graph")
|
| 439 |
+
outputs = pytree.tree_leaves(outputs)
|
| 440 |
+
if len(outputs) != len(xs):
|
| 441 |
+
raise AssertionError(
|
| 442 |
+
f"expected combine_fn to return {len(xs)} results but got {len(outputs)}"
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
xs_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [
|
| 446 |
+
first_slice_copy(x) for x in xs
|
| 447 |
+
]
|
| 448 |
+
output_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [
|
| 449 |
+
c.meta["val"] for c in outputs
|
| 450 |
+
]
|
| 451 |
+
check_meta_consistency(
|
| 452 |
+
xs_fake_tensors, output_fake_tensors, "init", "carry", include_contiguity=False
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
_, combine_graph_name = unique_graph_id(
|
| 456 |
+
proxy_mode, prefix="associative_scan_combine_graph"
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
proxy_mode.tracer.root.register_module(combine_graph_name, combine_graph)
|
| 460 |
+
|
| 461 |
+
args = (combine_graph, xs, additional_inputs)
|
| 462 |
+
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args)
|
| 463 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 464 |
+
"call_function", func_overload, proxy_args, {}, name="associative_scan"
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
with disable_proxy_modes_tracing():
|
| 468 |
+
out = tuple(aten.clone(x) for x in xs)
|
| 469 |
+
|
| 470 |
+
return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
@associative_scan_op.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 474 |
+
def associative_scan_op_dense(combine_fn, xs, additional_inputs):
|
| 475 |
+
return generic_associative_scan(combine_fn, xs, additional_inputs=additional_inputs)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class AssociativeScanAutogradOp(torch.autograd.Function):
|
| 479 |
+
r""" associative_scan
|
| 480 |
+
Example::
|
| 481 |
+
xs = torch.arange(1, 5) = [1, 2, 3, 4]
|
| 482 |
+
|
| 483 |
+
def combine_fn(a: torch.Tensor, b: torch.Tensor):
|
| 484 |
+
return a * b
|
| 485 |
+
|
| 486 |
+
ys = associative_scan(comine_fn, xs),
|
| 487 |
+
which can be unpacked as:
|
| 488 |
+
ys0 = xs0 = 1
|
| 489 |
+
ys1 = combine_fn(ys0, xs1) = combine_fn(1, 2) = 2
|
| 490 |
+
...
|
| 491 |
+
ysT = combine_fn(ys(T-1), xsT) = combine_fn(6, 4) = 24
|
| 492 |
+
ys = [1, 2, 6, 24]
|
| 493 |
+
|
| 494 |
+
This creates a recursive data dependency structure where each output yst
|
| 495 |
+
depends on all prior inputs xs0 through xst. The dependency can be visualized as:
|
| 496 |
+
|
| 497 |
+
Level 0 (Input): xs0 xs1 xs2 xs3 xs4
|
| 498 |
+
\ / | | |
|
| 499 |
+
\ / | | |
|
| 500 |
+
Level 1: ys1 ───────┘ | |
|
| 501 |
+
\ / |
|
| 502 |
+
\ / |
|
| 503 |
+
Level 2: ys2 ────────┘ |
|
| 504 |
+
\ /
|
| 505 |
+
\ /
|
| 506 |
+
Level 3: ys3 ────────────┘
|
| 507 |
+
\
|
| 508 |
+
\
|
| 509 |
+
Level 4: ys4
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
We could get the following backward gradient graph:
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
Level 0 (output): g_xs0 g_xs1 g_xs2 g_xs3 g_xs4
|
| 516 |
+
\ / | | |
|
| 517 |
+
\ / | | |
|
| 518 |
+
Level 1: gl_ys1 ─> g_ys1 ──────┘ | |
|
| 519 |
+
\ / |
|
| 520 |
+
\ / |
|
| 521 |
+
Level 2: gl_ys2 ─> g_ys2 ────────┘ |
|
| 522 |
+
\ /
|
| 523 |
+
\ /
|
| 524 |
+
Level 3: gl_ys3 ─> g_ys3 ────────────┘
|
| 525 |
+
\
|
| 526 |
+
\
|
| 527 |
+
Level 4: gl_ys4 ─> g_ys4,
|
| 528 |
+
|
| 529 |
+
where gl_y1 is the gradient of the loss with respect to ys1 and the input of backward.
|
| 530 |
+
|
| 531 |
+
To calculate the gradients of the inputs, the chain rule suggests:
|
| 532 |
+
|
| 533 |
+
g_xs0 = g_ys1
|
| 534 |
+
g_xs1 = g_ys1 * bw(ys0, xs1) = g_ys1 * bwxs01
|
| 535 |
+
g_xs2 = g_ys2 * bw(ys1, xs2) = g_ys2 * bwxs12
|
| 536 |
+
g_xs3 = g_ys3 * bw(ys2, xs3) = g_ys3 * bwxs23
|
| 537 |
+
g_xs4 = g_ys4 * bw(ys3, xs4) = g_ys4 * bwxs34
|
| 538 |
+
|
| 539 |
+
Notice the bw(...) is just the single step bw (instantaneous gradients), whose formula can be computed from combine_fn.
|
| 540 |
+
For example bw(ys3, xs4) (also abbreviated with bwxs34) computes the gradients ∂/∂xs4 combine_fn(ys3, xs4).
|
| 541 |
+
Similarly, bw(ys4, ys3) (also abbreviated with bwys43) computes the gradients ∂/∂ys3 combine_fn(ys3, xs4).
|
| 542 |
+
|
| 543 |
+
Let's break down how to calculate g_ys by recursively substituting the unknowns:
|
| 544 |
+
|
| 545 |
+
g_ys1 = gl_ys1 + g_ys2 * bw(ys2, ys1)
|
| 546 |
+
= gl_ys1 + (gl_ys2 + g_ys3 * bw(ys3, ys2)) * bw(ys2, ys1)
|
| 547 |
+
= gl_ys1 + gl_ys2 * bw(ys2, ys1) + g_ys3 * bw(ys3, ys2) * bw(y2, y1)
|
| 548 |
+
= gl_ys1 + gl_ys2 * bw(ys2, ys1) + gl_ys3 * bw(ys3, ys2) * bw(y2, y1) \
|
| 549 |
+
+ g_ys4 * bw(ys4, ys3) * bw(ys3, ys2) * bw(ys2, ys1)
|
| 550 |
+
= gl_ys1 + gl_ys2 * bw(ys2, ys1) + gl_ys3 * bw(ys3, ys2) * bw(y2, y1) \
|
| 551 |
+
+ gl_ys4 * bw(ys4, ys3) * bw(ys3, ys2) * bw(ys2, ys1)
|
| 552 |
+
|
| 553 |
+
Let's do the same for all the g_ys:
|
| 554 |
+
g_ys2 = gl_ys2 + gl_ys3 * bw(ys3, ys2) + gl_y4 * bw(ys4, ys3) * bw(ys3, ys2)
|
| 555 |
+
g_ys3 = gl_ys3 + gl_ys4 * bw(ys4, ys3)
|
| 556 |
+
g_ys4 = gl_ys4
|
| 557 |
+
|
| 558 |
+
Notice that the above can be re-written as columnwise multiplication of y_mat and gl_ys:
|
| 559 |
+
|
| 560 |
+
g_ys1 1, bwys21, bwys321, bwys4321 gl_ys1
|
| 561 |
+
g_ys2 = 0, 1 , bwys321, bwys4321 . gl_ys2
|
| 562 |
+
g_ys3 0, 0 , 1 , bwys4321 gl_ys3
|
| 563 |
+
g_ys4 0, 0 , 0 , 1 gl_ys4,
|
| 564 |
+
|
| 565 |
+
where bwys21 is an abbreviation for bw(ys2, ys1),
|
| 566 |
+
bwys321 is an abbreviation for bw(ys3, ys2) * bw(ys2, ys1) so on and so forth.
|
| 567 |
+
|
| 568 |
+
We could effectively compute the upper triangular matrix y_mat with:
|
| 569 |
+
cumprod([1, bwys21, bwys32, bwys43]) then masking out the values as needed.
|
| 570 |
+
Thus, only [1, bwys21, bwys32, bwys43] are required to compute the y_mat.
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
References: https://justintchiu.com/blog/pscan_diff/
|
| 574 |
+
|
| 575 |
+
NOTE: [associative_scan autograd implementation]
|
| 576 |
+
|
| 577 |
+
The forward of associative_scan can be computed with the following steps:
|
| 578 |
+
|
| 579 |
+
1.) Compute the forward output of the associative_scan
|
| 580 |
+
ys = associative_scan(combine_fn, xs, additional_inputs)
|
| 581 |
+
|
| 582 |
+
The backward of associative_scan can be computed with the following steps:
|
| 583 |
+
|
| 584 |
+
2.) Prepare the backward graph
|
| 585 |
+
We prepare the backward graph to be used in the backward function.
|
| 586 |
+
We utilize ``create_bw_fn`` to generate the joint function:
|
| 587 |
+
combine_fn_bw = create_bw_fn(combine_fn, operands)
|
| 588 |
+
where operands = [ys{t-1}, xst, additional_inputs]
|
| 589 |
+
|
| 590 |
+
3.) Materialize the ``combine_fn_bw``
|
| 591 |
+
This is required because torch.compile and torch.autograd.grad
|
| 592 |
+
cannot trace through the joint backward function dynamically.
|
| 593 |
+
|
| 594 |
+
4.) Compute the single step bw (instantaneous gradients) at every step t
|
| 595 |
+
bwys{t-1}, bwxst = combine_fn_bw(ys{t-1}, xst, 1.)
|
| 596 |
+
Here we pass 1 as the upstream gradient to obtain the local partial derivatives.
|
| 597 |
+
|
| 598 |
+
This gives:
|
| 599 |
+
bwys = [bw(ys1, ys0), bw(ys2, ys1), ..., bw(ysT, ys{T-1})]
|
| 600 |
+
bwxs = [bw(ys1, xs0), bw(ys2, xs1), ..., bw(ys{T-1}, xsT)]
|
| 601 |
+
|
| 602 |
+
5.) Compute the gradient transition matrix y_mat
|
| 603 |
+
|
| 604 |
+
As shown in the example above, each input xst affects all later outputs ysi for i ≥ t.
|
| 605 |
+
According to the chain rule, each such path contributes a product of local gradients g_ysk.
|
| 606 |
+
|
| 607 |
+
For example:
|
| 608 |
+
∂ysT/∂xst = ∂ysT/∂ys{T-1} * ∂ys{T-1}/∂ys{T-2} * ... * ∂ys{t+1}/∂yst * ∂yst/∂xst
|
| 609 |
+
= bw(ysT, ys{T-1}) * bw(ys{T-1}, ys{T-2}) * ... * bw(ys{t+1}, yst) * bw(ys{t-1}, xst)
|
| 610 |
+
|
| 611 |
+
This motivates the use of a cumulative product over bwys to compute all such paths efficiently.
|
| 612 |
+
|
| 613 |
+
We now construct the matrix of gradient transition paths:
|
| 614 |
+
|
| 615 |
+
5.1 Repeat g_y values to form the base matrix
|
| 616 |
+
y_mat = [[1, bwys21, bwys32, bwys43],
|
| 617 |
+
[1, bwys21, bwys32, bwys43],
|
| 618 |
+
[1, bwys21, bwys32, bwys43],
|
| 619 |
+
[1, bwys21, bwys32, bwys43]]
|
| 620 |
+
|
| 621 |
+
5.2 Mask the lower triangle (inclusive) with 1s
|
| 622 |
+
y_mat = [[1, bwys21, bwys32, bwys43],
|
| 623 |
+
[1, 1 , bwys32, bwys43],
|
| 624 |
+
[1, 1 , 1 , bwys43],
|
| 625 |
+
[1, 1 , 1 , 1 ]]
|
| 626 |
+
|
| 627 |
+
5.3 Apply cumulative product row-wise
|
| 628 |
+
y_mat = cumprod(y_mat, dim=1)
|
| 629 |
+
Resulting in:
|
| 630 |
+
y_mat = [[1, bwys21, bwys32 * bwys21, bwys43 * bwys32 * bwys21],
|
| 631 |
+
[1, 1 , bwys32 , bwys43 * bwys32 ],
|
| 632 |
+
[1, 1 , 1 , bwys43 ],
|
| 633 |
+
[1, 1 , 1 , 1 ]]
|
| 634 |
+
|
| 635 |
+
5.4 Zero out the lower triangle (exclusive)
|
| 636 |
+
Final y_mat:
|
| 637 |
+
y_mat = [[1, bwys21, bwys32 * bwys21, bwys43 * bwys32 * bwys21],
|
| 638 |
+
[0, 1 , bwys32 , bwys43 * bwys32 ],
|
| 639 |
+
[0, 0 , 1 , bwys43 ],
|
| 640 |
+
[0, 0 , 0 , 1 ]]
|
| 641 |
+
|
| 642 |
+
6.) Scale the y_mat with the upstream gradients gl_ys
|
| 643 |
+
scaled_y_mat = y_mat * gl_ys
|
| 644 |
+
Each entry now holds the full contribution of ∂L/∂ysj to ∂L/∂xsi via the path through ysj.
|
| 645 |
+
|
| 646 |
+
7.) Reduce the scaled_y_mat with a row-wise sum
|
| 647 |
+
summed_y_mat = scaled_y_mat.sum(dim=1)
|
| 648 |
+
This accumulates all downstream contributions for each xst.
|
| 649 |
+
|
| 650 |
+
8.) Scale with the instantaneous input gradients bwxs
|
| 651 |
+
g_xs = summed_y_mat * bwxs
|
| 652 |
+
|
| 653 |
+
This gives the final input gradients:
|
| 654 |
+
g_xs = [∂L/∂xs0, ∂L/∂xs1, ..., ∂L/∂xsT]
|
| 655 |
+
|
| 656 |
+
NOTE: [scan partial grad handling]
|
| 657 |
+
If any element of xs or of the outputs does not require gradients
|
| 658 |
+
(i.e., requires_grad=False), then the corresponding gradients will be returned
|
| 659 |
+
as tensors of zeros with the same shape as the element.
|
| 660 |
+
"""
|
| 661 |
+
|
| 662 |
+
@staticmethod
|
| 663 |
+
# pyrefly: ignore [bad-override]
|
| 664 |
+
def forward(
|
| 665 |
+
ctx,
|
| 666 |
+
combine_fn,
|
| 667 |
+
num_xs,
|
| 668 |
+
num_additional_inputs,
|
| 669 |
+
*operands,
|
| 670 |
+
):
|
| 671 |
+
ctx._num_xs = num_xs
|
| 672 |
+
ctx._num_additional_inputs = num_additional_inputs
|
| 673 |
+
ctx._combine_fn = combine_fn
|
| 674 |
+
xs, additional_inputs = split_into_chunks(
|
| 675 |
+
operands, [num_xs, num_additional_inputs]
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
scan_length = xs[0].shape[0]
|
| 679 |
+
ctx._scan_length = scan_length
|
| 680 |
+
|
| 681 |
+
# We snapshot the dispatch keys in forward for materializing the
|
| 682 |
+
# the bw_graph in backward.
|
| 683 |
+
ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set()
|
| 684 |
+
ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set()
|
| 685 |
+
|
| 686 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 687 |
+
# 1.) Compute the forward output of the associative_scan
|
| 688 |
+
ys = associative_scan_op(combine_fn, xs, additional_inputs)
|
| 689 |
+
save_values_for_backward(ctx, list(operands) + list(ys))
|
| 690 |
+
|
| 691 |
+
return (*ys,)
|
| 692 |
+
|
| 693 |
+
@staticmethod
|
| 694 |
+
def backward(ctx, *gl_ys):
|
| 695 |
+
r"""
|
| 696 |
+
This function computes the gradients of the scan operation.
|
| 697 |
+
For a detailed description see the document above.
|
| 698 |
+
|
| 699 |
+
Args:
|
| 700 |
+
flat_grads (torch.Tensor): The tensor of upstream gradients, or a nested pytree of tensors.
|
| 701 |
+
E.g.: Gradient of the loss with respect to the forward output ys
|
| 702 |
+
"""
|
| 703 |
+
|
| 704 |
+
# The backward of associative_scan is always performed on the first dimension
|
| 705 |
+
dim = 0
|
| 706 |
+
scan_length = ctx._scan_length
|
| 707 |
+
num_xs = ctx._num_xs
|
| 708 |
+
num_additional_inputs = ctx._num_additional_inputs
|
| 709 |
+
|
| 710 |
+
# Extract the inputs to the forward path and outputs from the forward path
|
| 711 |
+
flat_args = saved_values(ctx)
|
| 712 |
+
xs, additional_inputs, outs = split_into_chunks(
|
| 713 |
+
flat_args, [num_xs, num_additional_inputs, num_xs]
|
| 714 |
+
)
|
| 715 |
+
ndim = outs[0].ndim
|
| 716 |
+
|
| 717 |
+
# First_slice_copy does not keep the original requires_grad flag,
|
| 718 |
+
# but we need it here in order to compute the correcte gradients
|
| 719 |
+
xs_slices = first_slice_copy_with_grad(itertools.chain(xs, xs))
|
| 720 |
+
|
| 721 |
+
# Construct the operands from the forward, fw_operands
|
| 722 |
+
# and the operands for a single event t of the forward, fw_operands_slice
|
| 723 |
+
fw_operands = (*xs, *additional_inputs)
|
| 724 |
+
fw_operands_slice = (*xs_slices, *additional_inputs)
|
| 725 |
+
|
| 726 |
+
# 2.) Prepare the backward graph
|
| 727 |
+
combine_fn_bw = create_bw_fn(ctx._combine_fn, fw_operands_slice)
|
| 728 |
+
|
| 729 |
+
# 3.) Materialize the ``combine_fn_bw``
|
| 730 |
+
# TODO: we need to materialize the bw graphs because dynamo is unable to
|
| 731 |
+
# trace through the joint function when torch.compile torch.autograd.grad.
|
| 732 |
+
combine_fn_bw_gm = materialize_as_graph(
|
| 733 |
+
combine_fn_bw,
|
| 734 |
+
(
|
| 735 |
+
*fw_operands_slice,
|
| 736 |
+
*[first_slice_copy(o) for o in outs],
|
| 737 |
+
),
|
| 738 |
+
ctx._fw_include_key_set,
|
| 739 |
+
ctx._fw_exclude_key_set,
|
| 740 |
+
force_enable_grad=True,
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
# vmap joint graph over scan dimension to compute the individual
|
| 744 |
+
# gradients for each time slice ``t`` in parallel.
|
| 745 |
+
# This computation can be parallelized, as these are just the instantaneous gradients and not the full chain-rule
|
| 746 |
+
# pyrefly: ignore [bad-argument-type]
|
| 747 |
+
mapped_combine_fn_bw_gm = torch.vmap(combine_fn_bw_gm, 0, 0)
|
| 748 |
+
|
| 749 |
+
# 4.) Compute the single step bw (instantaneous gradients) at every step ``t``
|
| 750 |
+
# Use a ones_like tensor in order not to scale the bwyst and bwxst,
|
| 751 |
+
# with the upstream gradients yet.
|
| 752 |
+
# Note: All bwyst and bwxst are computed in parallel, thus the tensors bwys and bwxs are the result.
|
| 753 |
+
dummy_upstream_grad = (torch.ones_like(x) for x in gl_ys)
|
| 754 |
+
grads = mapped_combine_fn_bw_gm(
|
| 755 |
+
*(o.roll(1, dim) for o in outs), *fw_operands, *dummy_upstream_grad
|
| 756 |
+
)
|
| 757 |
+
bwys, bwxs = split_into_chunks(grads, [num_xs, num_xs])
|
| 758 |
+
|
| 759 |
+
def compute_y_mat(bwys: torch.Tensor) -> torch.Tensor:
|
| 760 |
+
# Prepare a ones and a zeros helper mask in order to easily compute the y_mat
|
| 761 |
+
def compute_helper_tril_mask(diagonal):
|
| 762 |
+
def expand_masks(mask):
|
| 763 |
+
for _ in range(ndim - 1):
|
| 764 |
+
mask = mask.unsqueeze(-1)
|
| 765 |
+
return mask
|
| 766 |
+
|
| 767 |
+
tril_mask = torch.tril(
|
| 768 |
+
torch.ones(
|
| 769 |
+
scan_length, scan_length, device=bwys.device, dtype=torch.bool
|
| 770 |
+
),
|
| 771 |
+
diagonal=diagonal,
|
| 772 |
+
)
|
| 773 |
+
tril_mask = expand_masks(tril_mask)
|
| 774 |
+
tril_mask = tril_mask.expand(-1, -1, *bwys.shape[1:])
|
| 775 |
+
return tril_mask
|
| 776 |
+
|
| 777 |
+
# The ones mask is used to fill the main diagonal and all elements below it with 1s
|
| 778 |
+
ones_mask = compute_helper_tril_mask(0)
|
| 779 |
+
|
| 780 |
+
# The zero mask is used to set all elements below the main diagonal to 0
|
| 781 |
+
zeros_mask = compute_helper_tril_mask(-1)
|
| 782 |
+
|
| 783 |
+
# 5.1) Repeat the elements of bwys to form the square matrix
|
| 784 |
+
y_mat = bwys.unsqueeze(dim).repeat_interleave(scan_length, dim)
|
| 785 |
+
|
| 786 |
+
# 5.2) Fill the lower triangular part, including the diagonal,
|
| 787 |
+
# of the h_mat with 1s. I.e., use the ones_mask to fill with 1s.
|
| 788 |
+
y_mat.masked_fill_(ones_mask, 1.0)
|
| 789 |
+
|
| 790 |
+
# 5.3) Compute the cumulative products across dim + 1
|
| 791 |
+
y_mat = y_mat.cumprod(dim=dim + 1)
|
| 792 |
+
|
| 793 |
+
# 5.4) Replace the elements we filled with 1s before with 0s
|
| 794 |
+
y_mat.masked_fill_(zeros_mask, 0.0)
|
| 795 |
+
|
| 796 |
+
return y_mat
|
| 797 |
+
|
| 798 |
+
def compute_grad(bwxs, bwys, gl_ys):
|
| 799 |
+
# Set the first gradient component of bwxs to 1.0, per definition.
|
| 800 |
+
torch.select(bwxs, dim, 0).fill_(1.0)
|
| 801 |
+
|
| 802 |
+
# 5.) Compute the gradient transition matrix
|
| 803 |
+
y_mat = compute_y_mat(bwys)
|
| 804 |
+
|
| 805 |
+
# 6.) scale the y_mat with the upstream gradients gl_ys
|
| 806 |
+
scaled_y_mat = y_mat * gl_ys
|
| 807 |
+
|
| 808 |
+
# 7.) Reduce the y_mat with sum along the columns to get the total contributions for xs_t
|
| 809 |
+
summed_y_mat = scaled_y_mat.sum(dim + 1)
|
| 810 |
+
|
| 811 |
+
# 8.) Scale with the bwxs to obtain the final gradients g_xs
|
| 812 |
+
g_xs = summed_y_mat * bwxs
|
| 813 |
+
|
| 814 |
+
return g_xs
|
| 815 |
+
|
| 816 |
+
# Stack all leaves of the gradients along the first dimension.
|
| 817 |
+
# This is useful as later the gradients of those leaves can be computed in parallel.
|
| 818 |
+
bwxs_stacked_leaves = torch.stack(bwxs)
|
| 819 |
+
bwys_stacked_leaves = torch.stack(bwys)
|
| 820 |
+
gl_ys_stacked_leaves = torch.stack(gl_ys)
|
| 821 |
+
|
| 822 |
+
# The compute_grad function is parallelized across all individual leaves of xs
|
| 823 |
+
# as these gradients can be computed independently from each other
|
| 824 |
+
# TODO: torch.vmap may create composability issues
|
| 825 |
+
compute_grad_mapped = torch.vmap(compute_grad, 0, 0)
|
| 826 |
+
|
| 827 |
+
g_xs = compute_grad_mapped(
|
| 828 |
+
bwxs_stacked_leaves, bwys_stacked_leaves, gl_ys_stacked_leaves
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
# TODO: Currently the gradients for the additional_inputs are not computed properly
|
| 832 |
+
return *[None] * 3, *g_xs, *[None] * num_additional_inputs
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
@associative_scan_op.py_autograd_impl
|
| 836 |
+
def associative_scan_autograd(combine_fn, xs, additional_inputs):
|
| 837 |
+
num_xs = len(xs)
|
| 838 |
+
num_additional_inputs = len(additional_inputs)
|
| 839 |
+
|
| 840 |
+
if num_additional_inputs > 0:
|
| 841 |
+
raise RuntimeError(
|
| 842 |
+
"Associative_scan does currently not support gradients for lifted parameters!"
|
| 843 |
+
)
|
| 844 |
+
|
| 845 |
+
flat_out = AssociativeScanAutogradOp.apply(
|
| 846 |
+
combine_fn,
|
| 847 |
+
num_xs,
|
| 848 |
+
num_additional_inputs,
|
| 849 |
+
*(tuple(xs) + tuple(additional_inputs)),
|
| 850 |
+
)
|
| 851 |
+
return (*flat_out,)
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
@associative_scan_op.py_impl(ProxyTorchDispatchMode)
|
| 855 |
+
def associative_scan_proxy_mode(mode, combine_fn, xs, additional_inputs):
|
| 856 |
+
return trace_associative_scan(
|
| 857 |
+
mode, associative_scan_op, combine_fn, xs, additional_inputs
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
@associative_scan_op.py_impl(FakeTensorMode)
|
| 862 |
+
def assoiciative_scan_fake_tensor_mode(mode, combine_fn, xs, additional_inputs):
|
| 863 |
+
with mode:
|
| 864 |
+
return tuple(x.clone() for x in xs)
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
@associative_scan_op.py_functionalize_impl
|
| 868 |
+
def associative_scan_functionalize(ctx, combine_fn, xs, additional_inputs):
|
| 869 |
+
from torch._higher_order_ops.utils import _check_alias_and_mutation
|
| 870 |
+
|
| 871 |
+
unwrapped_xs = ctx.unwrap_tensors(xs)
|
| 872 |
+
unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs)
|
| 873 |
+
with ctx.redispatch_to_next():
|
| 874 |
+
functional_combine_fn = ctx.functionalize(
|
| 875 |
+
_maybe_run_with_interpreter(combine_fn)
|
| 876 |
+
)
|
| 877 |
+
pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
|
| 878 |
+
sample_unwrapped_xs_sliced = [
|
| 879 |
+
first_slice_copy(inp) for inp in itertools.chain(unwrapped_xs, unwrapped_xs)
|
| 880 |
+
]
|
| 881 |
+
sample_inputs = list(
|
| 882 |
+
itertools.chain(
|
| 883 |
+
sample_unwrapped_xs_sliced,
|
| 884 |
+
unwrapped_additional_inputs,
|
| 885 |
+
)
|
| 886 |
+
)
|
| 887 |
+
_check_alias_and_mutation(
|
| 888 |
+
combine_fn, sample_inputs, "associative_scan", pre_dispatch
|
| 889 |
+
)
|
| 890 |
+
ret = associative_scan_op(
|
| 891 |
+
functional_combine_fn,
|
| 892 |
+
unwrapped_xs,
|
| 893 |
+
unwrapped_additional_inputs,
|
| 894 |
+
)
|
| 895 |
+
return ctx.wrap_tensors(ret)
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
def _fake_associative_scan(combine_fn, xs, dim, reverse=False):
|
| 899 |
+
inp_leaves, spec = pytree.tree_flatten(xs)
|
| 900 |
+
result_flat: list[Any] = []
|
| 901 |
+
num_leaves = len(inp_leaves)
|
| 902 |
+
op = reversed if reverse else lambda x: x
|
| 903 |
+
|
| 904 |
+
for ind in op(range(inp_leaves[0].size(dim))):
|
| 905 |
+
r = [
|
| 906 |
+
inp_leaves[leave_ind][(slice(None),) * dim + (ind,)]
|
| 907 |
+
for leave_ind in range(num_leaves)
|
| 908 |
+
]
|
| 909 |
+
if (ind > 0 and not reverse) or (
|
| 910 |
+
ind < (inp_leaves[0].size(dim) - 1) and reverse
|
| 911 |
+
):
|
| 912 |
+
r = combine_fn(
|
| 913 |
+
pytree.tree_unflatten(result_flat[-1], spec),
|
| 914 |
+
pytree.tree_unflatten(r, spec),
|
| 915 |
+
)
|
| 916 |
+
r_flat, _ = pytree.tree_flatten(r)
|
| 917 |
+
result_flat.append(r_flat)
|
| 918 |
+
|
| 919 |
+
results = [
|
| 920 |
+
torch.stack([e[leave_ind] for e in op(result_flat)], dim)
|
| 921 |
+
for leave_ind in range(num_leaves)
|
| 922 |
+
]
|
| 923 |
+
return pytree.tree_unflatten(results, spec)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/auto_functionalize.py
ADDED
|
@@ -0,0 +1,1090 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import warnings
|
| 3 |
+
from abc import ABC, abstractmethod
|
| 4 |
+
from collections.abc import Callable, Sequence
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import Any, get_args
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch._library.utils as library_utils
|
| 10 |
+
import torch.utils._pytree as pytree
|
| 11 |
+
from torch import Tensor
|
| 12 |
+
from torch._C import DispatchKey
|
| 13 |
+
from torch._higher_order_ops.utils import (
|
| 14 |
+
_has_gen_schema,
|
| 15 |
+
call_op,
|
| 16 |
+
HopInstance,
|
| 17 |
+
HopSchema,
|
| 18 |
+
materialize_callable_in_args,
|
| 19 |
+
unique_graph_id,
|
| 20 |
+
)
|
| 21 |
+
from torch._ops import HigherOrderOperator, OperatorBase, OpOverload
|
| 22 |
+
from torch._prims_common import clone_preserve_strides
|
| 23 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 24 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 25 |
+
disable_proxy_modes_tracing,
|
| 26 |
+
ProxyTorchDispatchMode,
|
| 27 |
+
track_tensor_tree,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class SchemaHolder:
|
| 32 |
+
def __init__(self, schema: torch.FunctionSchema):
|
| 33 |
+
self.schema = schema
|
| 34 |
+
|
| 35 |
+
def __eq__(self, other):
|
| 36 |
+
return self.schema == other.schema
|
| 37 |
+
|
| 38 |
+
def __hash__(self) -> int:
|
| 39 |
+
return hash(self.schema)
|
| 40 |
+
|
| 41 |
+
@classmethod
|
| 42 |
+
def from_tree_spec(cls, tree_spec: pytree.TreeSpec):
|
| 43 |
+
if tree_spec is None:
|
| 44 |
+
raise AssertionError("tree_spec cannot be None")
|
| 45 |
+
return cls(pytree.tree_unflatten([], tree_spec).schema)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# register_constant allows us to get a tree_spec from pytree.tree_flatten(SchemaHolder(FunctionSchema)).
|
| 49 |
+
# The tree_spec is proxable in the graph and we can get back the schema via
|
| 50 |
+
# schema = pytree.tree_unflatten([], tree_spec).schema
|
| 51 |
+
pytree.register_constant(SchemaHolder)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def get_base(tensor):
|
| 55 |
+
if torch.is_inference_mode_enabled():
|
| 56 |
+
return tensor._inference_mode_base
|
| 57 |
+
else:
|
| 58 |
+
return tensor._base
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class ViewInfo(ABC):
|
| 62 |
+
base_index: int
|
| 63 |
+
|
| 64 |
+
def __init__(self, base_index):
|
| 65 |
+
self.base_index = base_index
|
| 66 |
+
|
| 67 |
+
@abstractmethod
|
| 68 |
+
def regenerate_view(self, bases_list: list[Tensor]):
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass
|
| 73 |
+
class AsStridedViewInfo(ViewInfo):
|
| 74 |
+
size: Sequence[int | torch.SymInt]
|
| 75 |
+
stride: Sequence[int | torch.SymInt]
|
| 76 |
+
storage_offset: int
|
| 77 |
+
|
| 78 |
+
def __init__(self, base_index, size, stride, storage_offset):
|
| 79 |
+
super().__init__(base_index)
|
| 80 |
+
self.size = size
|
| 81 |
+
self.stride = stride
|
| 82 |
+
self.storage_offset = storage_offset
|
| 83 |
+
|
| 84 |
+
def regenerate_view(self, bases_list: list[Tensor]):
|
| 85 |
+
return torch.as_strided(
|
| 86 |
+
bases_list[self.base_index],
|
| 87 |
+
self.size,
|
| 88 |
+
self.stride,
|
| 89 |
+
self.storage_offset,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@dataclass
|
| 94 |
+
class SliceViewInfo(ViewInfo):
|
| 95 |
+
dim: int | torch.SymInt
|
| 96 |
+
start: int | torch.SymInt
|
| 97 |
+
end: int | torch.SymInt
|
| 98 |
+
|
| 99 |
+
def __init__(self, base_index, dim, start, end):
|
| 100 |
+
super().__init__(base_index)
|
| 101 |
+
self.dim = dim
|
| 102 |
+
self.start = start
|
| 103 |
+
self.end = end
|
| 104 |
+
|
| 105 |
+
def regenerate_view(self, bases_list: list[Tensor]):
|
| 106 |
+
return torch.ops.aten.slice.Tensor(
|
| 107 |
+
bases_list[self.base_index], self.dim, self.start, self.end
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@dataclass
|
| 112 |
+
class AliasViewInfo(ViewInfo):
|
| 113 |
+
def __init__(self, base_index):
|
| 114 |
+
super().__init__(base_index)
|
| 115 |
+
|
| 116 |
+
def regenerate_view(self, bases_list: list[Tensor]):
|
| 117 |
+
return torch.ops.aten.alias.default(bases_list[self.base_index])
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@dataclass
|
| 121 |
+
class NotView(ViewInfo):
|
| 122 |
+
def __init__(self, base_index):
|
| 123 |
+
super().__init__(base_index)
|
| 124 |
+
|
| 125 |
+
def regenerate_view(self, bases_list: list[Tensor]):
|
| 126 |
+
return bases_list[self.base_index]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def is_alias(base, tensor):
|
| 130 |
+
from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq
|
| 131 |
+
|
| 132 |
+
return all(
|
| 133 |
+
statically_known_true(a)
|
| 134 |
+
for a in [
|
| 135 |
+
sym_eq(base.storage_offset(), tensor.storage_offset()),
|
| 136 |
+
sym_eq(base.stride(), tensor.stride()),
|
| 137 |
+
sym_eq(base.size(), tensor.size()),
|
| 138 |
+
]
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# return None or (dim, start, end)
|
| 143 |
+
def try_use_slice(base, tensor):
|
| 144 |
+
from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq
|
| 145 |
+
|
| 146 |
+
# This condition should never be triggered.
|
| 147 |
+
if is_alias(base, tensor):
|
| 148 |
+
return (0, 0, base.size()[0])
|
| 149 |
+
|
| 150 |
+
# TODO is there cases can we use slice even if stride or len(sizes) are not equal?
|
| 151 |
+
if not statically_known_true(sym_eq(tensor.stride(), base.stride())):
|
| 152 |
+
return None
|
| 153 |
+
if not statically_known_true(sym_eq(len(tensor.size()), len(base.size()))):
|
| 154 |
+
return None
|
| 155 |
+
|
| 156 |
+
dim = None
|
| 157 |
+
count = 0
|
| 158 |
+
for i in range(len(tensor.size())):
|
| 159 |
+
if base.size()[i] != tensor.size()[i]:
|
| 160 |
+
dim = i
|
| 161 |
+
count = count + 1
|
| 162 |
+
if count != 1:
|
| 163 |
+
return None
|
| 164 |
+
|
| 165 |
+
if tensor.storage_offset() % tensor.stride()[dim] != 0:
|
| 166 |
+
return None
|
| 167 |
+
start = tensor.storage_offset() // tensor.stride()[dim]
|
| 168 |
+
end = start + tensor.size()[dim]
|
| 169 |
+
return (dim, start, end)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def write_view_information_to_args(
|
| 173 |
+
mutable_arg_names: list[str],
|
| 174 |
+
mutable_arg_types: list[torch.Type],
|
| 175 |
+
kwargs: dict[str, Any],
|
| 176 |
+
arg_to_base_index: dict[str, Any],
|
| 177 |
+
):
|
| 178 |
+
"""
|
| 179 |
+
This function writes the view information into kwargs. It reads mutable_args from kwargs.
|
| 180 |
+
and uses arg_to_base_index and tensor information to write ViewInfo into kwargs.
|
| 181 |
+
mutable_arg_names: mutable custom operator arg names.
|
| 182 |
+
mutable_arg_types: mutable custom operator arg types.
|
| 183 |
+
kwargs: the original custom operator args.
|
| 184 |
+
arg_to_base_index: maps mutable_arg_name to int | [int] that refers to the base tensor that
|
| 185 |
+
corresponds to the input tensor
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
def write_single_view(prefix: str, tensor: Tensor, base_index: int):
|
| 189 |
+
if f"{prefix}_base_index" in kwargs:
|
| 190 |
+
raise AssertionError(f"{prefix}_base_index already in kwargs")
|
| 191 |
+
if f"{prefix}_size" in kwargs:
|
| 192 |
+
raise AssertionError(f"{prefix}_size already in kwargs")
|
| 193 |
+
if f"{prefix}_stride" in kwargs:
|
| 194 |
+
raise AssertionError(f"{prefix}_stride already in kwargs")
|
| 195 |
+
if f"{prefix}_storage_offset" in kwargs:
|
| 196 |
+
raise AssertionError(f"{prefix}_storage_offset already in kwargs")
|
| 197 |
+
|
| 198 |
+
if f"{prefix}_slice_dim" in kwargs:
|
| 199 |
+
raise AssertionError(f"{prefix}_slice_dim already in kwargs")
|
| 200 |
+
if f"{prefix}_slice_start" in kwargs:
|
| 201 |
+
raise AssertionError(f"{prefix}_slice_start already in kwargs")
|
| 202 |
+
if f"{prefix}_slice_end" in kwargs:
|
| 203 |
+
raise AssertionError(f"{prefix}_slice_end already in kwargs")
|
| 204 |
+
|
| 205 |
+
def use_as_strided(tensor):
|
| 206 |
+
kwargs[f"{prefix}_size"] = tensor.size()
|
| 207 |
+
kwargs[f"{prefix}_stride"] = tensor.stride()
|
| 208 |
+
kwargs[f"{prefix}_storage_offset"] = tensor.storage_offset()
|
| 209 |
+
|
| 210 |
+
def use_slice(dim, start, end):
|
| 211 |
+
kwargs[f"{prefix}_slice_dim"] = dim
|
| 212 |
+
kwargs[f"{prefix}_slice_start"] = start
|
| 213 |
+
kwargs[f"{prefix}_slice_end"] = end
|
| 214 |
+
|
| 215 |
+
def use_alias():
|
| 216 |
+
kwargs[f"{prefix}_alias"] = True
|
| 217 |
+
|
| 218 |
+
# The start if the function
|
| 219 |
+
if tensor is None:
|
| 220 |
+
kwargs[f"{prefix}_base_index"] = None
|
| 221 |
+
else:
|
| 222 |
+
base = get_base(tensor)
|
| 223 |
+
kwargs[f"{prefix}_base_index"] = base_index
|
| 224 |
+
if base is None:
|
| 225 |
+
# no need to add anything else other than _base_index
|
| 226 |
+
return
|
| 227 |
+
elif is_alias(base, tensor):
|
| 228 |
+
use_alias()
|
| 229 |
+
elif (slice_info := try_use_slice(base, tensor)) is not None:
|
| 230 |
+
use_slice(*slice_info)
|
| 231 |
+
else:
|
| 232 |
+
use_as_strided(tensor)
|
| 233 |
+
|
| 234 |
+
for arg_name, arg_type in zip(mutable_arg_names, mutable_arg_types):
|
| 235 |
+
arg = kwargs[arg_name]
|
| 236 |
+
if library_utils.is_tensorlist_like_type(arg_type):
|
| 237 |
+
if arg is None:
|
| 238 |
+
kwargs[f"_{arg_name}_length"] = None
|
| 239 |
+
else:
|
| 240 |
+
kwargs[f"_{arg_name}_length"] = len(arg)
|
| 241 |
+
for i, elem in enumerate(arg):
|
| 242 |
+
write_single_view(
|
| 243 |
+
f"_{arg_name}_{i}", elem, arg_to_base_index[arg_name][i]
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
elif library_utils.is_tensor_like_type(arg_type):
|
| 247 |
+
write_single_view(
|
| 248 |
+
f"_{arg_name}",
|
| 249 |
+
kwargs[arg_name],
|
| 250 |
+
arg_to_base_index.get(arg_name), # type: ignore[arg-type]
|
| 251 |
+
)
|
| 252 |
+
else:
|
| 253 |
+
raise RuntimeError(f"Unsupported type {arg_type}")
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
# Returns a dict of arg_name -> ViewInfo | [ViewInfo]
|
| 257 |
+
def read_view_information_from_args(
|
| 258 |
+
mutable_arg_names: list[str],
|
| 259 |
+
mutable_arg_types: list[torch.Type],
|
| 260 |
+
kwargs: dict[str, Any],
|
| 261 |
+
all_bases: list[Tensor],
|
| 262 |
+
):
|
| 263 |
+
"""
|
| 264 |
+
This reads the view information added by `write_view_information_to_args` from kwargs, pop them,
|
| 265 |
+
and returns a dict arg_name -> ViewInfo | [ViewInfo](if the input is list). that maps each mutable arg
|
| 266 |
+
to its view information.
|
| 267 |
+
mutable_arg_names: mutable custom operator arg names.
|
| 268 |
+
mutable_arg_types: mutable custom operator arg types.
|
| 269 |
+
kwargs : args of auto_functionalize(custom_op, kwargs)
|
| 270 |
+
"""
|
| 271 |
+
|
| 272 |
+
def get_arg(name):
|
| 273 |
+
return kwargs.pop(name)
|
| 274 |
+
|
| 275 |
+
def read_single_view(prefix):
|
| 276 |
+
base_index = get_arg(f"{prefix}_base_index")
|
| 277 |
+
if base_index is None:
|
| 278 |
+
return None
|
| 279 |
+
elif f"{prefix}_alias" in kwargs:
|
| 280 |
+
get_arg(f"{prefix}_alias")
|
| 281 |
+
return AliasViewInfo(base_index)
|
| 282 |
+
elif f"{prefix}_storage_offset" in kwargs:
|
| 283 |
+
# The view is regenerated using as_strided.
|
| 284 |
+
size = get_arg(f"{prefix}_size")
|
| 285 |
+
stride = get_arg(f"{prefix}_stride")
|
| 286 |
+
storage_offset = get_arg(f"{prefix}_storage_offset")
|
| 287 |
+
return AsStridedViewInfo(base_index, size, stride, storage_offset)
|
| 288 |
+
elif f"{prefix}_slice_dim" in kwargs:
|
| 289 |
+
dim = get_arg(f"{prefix}_slice_dim")
|
| 290 |
+
start = get_arg(f"{prefix}_slice_start")
|
| 291 |
+
end = get_arg(f"{prefix}_slice_end")
|
| 292 |
+
return SliceViewInfo(base_index, dim, start, end)
|
| 293 |
+
else:
|
| 294 |
+
# This means that the argument is the base tensor
|
| 295 |
+
return NotView(base_index)
|
| 296 |
+
|
| 297 |
+
args_view_info: dict[str, Any] = {}
|
| 298 |
+
for arg_name, arg_type in zip(mutable_arg_names, mutable_arg_types):
|
| 299 |
+
if library_utils.is_tensorlist_like_type(arg_type):
|
| 300 |
+
length = get_arg(f"_{arg_name}_length")
|
| 301 |
+
if length is None:
|
| 302 |
+
# The whole list is None.
|
| 303 |
+
args_view_info[arg_name] = None
|
| 304 |
+
else:
|
| 305 |
+
args_view_info[arg_name] = [
|
| 306 |
+
read_single_view(f"_{arg_name}_{i}") for i in range(length)
|
| 307 |
+
]
|
| 308 |
+
|
| 309 |
+
elif library_utils.is_tensor_like_type(arg_type):
|
| 310 |
+
args_view_info[arg_name] = read_single_view(f"_{arg_name}")
|
| 311 |
+
else:
|
| 312 |
+
raise RuntimeError(f"Unsupported type {arg_type}")
|
| 313 |
+
return args_view_info
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
# NOTE: [auto-functionalizing custom ops]
|
| 317 |
+
# Users may wish to torch.compile custom ops that mutate their inputs.
|
| 318 |
+
# torch.compile will automatically support this op without anyone needing
|
| 319 |
+
# to provide a functionalization kernel for it. Here's how.
|
| 320 |
+
#
|
| 321 |
+
# Let's say we have a hypothetical mylib::sin_(Tensor(a!) x) -> ()
|
| 322 |
+
# op. First, when FakeTensor sees this op:
|
| 323 |
+
# - If the schema says it returns nothing, we can generate a trivial
|
| 324 |
+
# FakeTensor rule for it (that returns nothing).
|
| 325 |
+
# - Otherwise, the user needs to provide a FakeTensor impl (fake impl)
|
| 326 |
+
#
|
| 327 |
+
# Next, when Python FunctionalTensor sees the op, it will functionalize
|
| 328 |
+
# it by emitting a call to an auto_functionalize(op, ["x"], {"x": ...})
|
| 329 |
+
# HOP and replacing the mutated inputs with corresponding outputs of this HOP.
|
| 330 |
+
# This HOP effectively runs the functional version of the op when
|
| 331 |
+
# called: it clones inputs that will be mutated, runs the op, and
|
| 332 |
+
# then returns (output, Tensors with the new values)
|
| 333 |
+
#
|
| 334 |
+
# auto_functionalize_v2 is an improved version of auto_functionalize that better handle
|
| 335 |
+
# re-inplacing views.
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class AutoFunctionalized(HigherOrderOperator):
|
| 339 |
+
"""auto_functionalized(_mutable_op, **kwargs)
|
| 340 |
+
|
| 341 |
+
This HOP runs a "functional" version of _mutable_op.
|
| 342 |
+
|
| 343 |
+
Concretely, it looks at all the arguments that are mutable through
|
| 344 |
+
_mutable_op's operator schema, clones those kwargs, runs
|
| 345 |
+
`out = _mutable_op(**kwargs)` with the cloned values, and then returns the
|
| 346 |
+
operator output concatenated with the cloned values that were mutated.
|
| 347 |
+
|
| 348 |
+
We have some restrictions on `_mutable_op`.
|
| 349 |
+
See `can_auto_functionalize` for the restrictions. We can likely lift
|
| 350 |
+
many of these if users request it.
|
| 351 |
+
|
| 352 |
+
The reason why _mutable_op is prefixed with an
|
| 353 |
+
underscore is to prevent collisions with kwarg names in **kwargs.
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
def __init__(self) -> None:
|
| 357 |
+
super().__init__("auto_functionalized", cacheable=True)
|
| 358 |
+
|
| 359 |
+
def __call__(
|
| 360 |
+
self,
|
| 361 |
+
/,
|
| 362 |
+
_mutable_op: OpOverload,
|
| 363 |
+
**kwargs: Any,
|
| 364 |
+
) -> tuple[Any, tuple[Tensor, ...]]:
|
| 365 |
+
if not can_auto_functionalize(_mutable_op):
|
| 366 |
+
raise AssertionError(f"Cannot auto-functionalize op {_mutable_op}")
|
| 367 |
+
if not isinstance(kwargs, dict):
|
| 368 |
+
raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}")
|
| 369 |
+
# pyrefly: ignore [missing-attribute]
|
| 370 |
+
return super().__call__(_mutable_op, **kwargs)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
auto_functionalized = AutoFunctionalized()
|
| 374 |
+
auto_functionalized.__module__ = "torch.ops.higher_order"
|
| 375 |
+
|
| 376 |
+
auto_functionalized.fallthrough(DispatchKey.AutogradCPU)
|
| 377 |
+
auto_functionalized.fallthrough(DispatchKey.AutogradCUDA)
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
_MutableOpType = OpOverload | HigherOrderOperator
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
class AutoFunctionalizedV2(HigherOrderOperator):
|
| 384 |
+
"""auto_functionalized_v2(_mutable_op, **kwargs)
|
| 385 |
+
|
| 386 |
+
This HOP runs a "functional" version of _mutable_op.
|
| 387 |
+
Unlike AutoFunctionalized, this version is improved to better handle
|
| 388 |
+
view tensors. This version is only used in non export mode.
|
| 389 |
+
"""
|
| 390 |
+
|
| 391 |
+
def __init__(self) -> None:
|
| 392 |
+
super().__init__("auto_functionalized_v2", cacheable=True)
|
| 393 |
+
|
| 394 |
+
def __call__(
|
| 395 |
+
self,
|
| 396 |
+
/,
|
| 397 |
+
_mutable_op: _MutableOpType,
|
| 398 |
+
**kwargs: Any,
|
| 399 |
+
) -> tuple[Any, tuple[Tensor, ...]]:
|
| 400 |
+
_op_to_check: OpOverload | HopInstance | None = None
|
| 401 |
+
if isinstance(_mutable_op, HigherOrderOperator):
|
| 402 |
+
_op_to_check = HopInstance(
|
| 403 |
+
_mutable_op,
|
| 404 |
+
SchemaHolder.from_tree_spec(kwargs.get("_op_schema")).schema, # type: ignore[arg-type]
|
| 405 |
+
)
|
| 406 |
+
else:
|
| 407 |
+
_op_to_check = _mutable_op
|
| 408 |
+
|
| 409 |
+
if _op_to_check is None:
|
| 410 |
+
raise AssertionError("_op_to_check cannot be None")
|
| 411 |
+
if not can_auto_functionalize(_op_to_check):
|
| 412 |
+
raise AssertionError(f"Cannot auto-functionalize op {_op_to_check}")
|
| 413 |
+
if not isinstance(kwargs, dict):
|
| 414 |
+
raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}")
|
| 415 |
+
# pyrefly: ignore [missing-attribute]
|
| 416 |
+
return super().__call__(_mutable_op, **kwargs)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
auto_functionalized_v2 = AutoFunctionalizedV2()
|
| 420 |
+
auto_functionalized_v2.__module__ = "torch.ops.higher_order"
|
| 421 |
+
|
| 422 |
+
auto_functionalized_v2.fallthrough(DispatchKey.AutogradCPU)
|
| 423 |
+
auto_functionalized_v2.fallthrough(DispatchKey.AutogradCUDA)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def can_auto_functionalize(
|
| 427 |
+
op: OperatorBase | HopInstance,
|
| 428 |
+
) -> bool:
|
| 429 |
+
if isinstance(op, HopInstance):
|
| 430 |
+
# HOPs that implement gen_schema and schema is not functional are auto_functionalizable.
|
| 431 |
+
if not _has_gen_schema(op._op):
|
| 432 |
+
return False
|
| 433 |
+
|
| 434 |
+
else:
|
| 435 |
+
if not isinstance(op, OpOverload):
|
| 436 |
+
return False
|
| 437 |
+
|
| 438 |
+
if torch._library.utils.is_builtin(op):
|
| 439 |
+
# We control the built-ins. These may (in rare cases)
|
| 440 |
+
# do input metadata mutation (which we have banned on custom ops)
|
| 441 |
+
return False
|
| 442 |
+
|
| 443 |
+
schema = op._schema
|
| 444 |
+
if not schema.is_mutable:
|
| 445 |
+
return False
|
| 446 |
+
schema = op._schema
|
| 447 |
+
|
| 448 |
+
for arg in schema.arguments:
|
| 449 |
+
if arg.alias_info is None:
|
| 450 |
+
continue
|
| 451 |
+
if not arg.alias_info.is_write:
|
| 452 |
+
continue
|
| 453 |
+
if torch._library.utils.is_tensor_like_type(arg.type):
|
| 454 |
+
continue
|
| 455 |
+
if torch._library.utils.is_tensorlist_like_type(arg.type):
|
| 456 |
+
continue
|
| 457 |
+
return False
|
| 458 |
+
|
| 459 |
+
if len(schema.returns) == 1 and isinstance(schema.returns[0].type, torch.NoneType):
|
| 460 |
+
# Skip schema returns -> None
|
| 461 |
+
return True
|
| 462 |
+
if isinstance(op, OpOverload):
|
| 463 |
+
# The returns of OpOverload must not alias anything
|
| 464 |
+
for ret in schema.returns:
|
| 465 |
+
if ret.alias_info is None and type(ret.type) is torch.TensorType:
|
| 466 |
+
continue
|
| 467 |
+
# Not yet supported: List[Tensor] return.
|
| 468 |
+
return False
|
| 469 |
+
if torch._C._dispatch_has_kernel_for_dispatch_key(op.name(), "Functionalize"):
|
| 470 |
+
return False
|
| 471 |
+
return True
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def get_mutable_args_from_schema(
|
| 475 |
+
schema: torch.FunctionSchema,
|
| 476 |
+
) -> tuple[list[str], list[torch.Type]]:
|
| 477 |
+
"""
|
| 478 |
+
Returns the list of argument names that get mutated according to the
|
| 479 |
+
schema and their types.
|
| 480 |
+
"""
|
| 481 |
+
mutable_args_names = [
|
| 482 |
+
arg.name
|
| 483 |
+
for arg in schema.arguments
|
| 484 |
+
if arg.alias_info is not None and arg.alias_info.is_write
|
| 485 |
+
]
|
| 486 |
+
|
| 487 |
+
mutable_args_types = [
|
| 488 |
+
arg.type
|
| 489 |
+
for arg in schema.arguments
|
| 490 |
+
if arg.alias_info is not None and arg.alias_info.is_write
|
| 491 |
+
]
|
| 492 |
+
return mutable_args_names, mutable_args_types # type: ignore[return-value]
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def get_mutable_args(op: OpOverload) -> tuple[list[str], list[torch.Type]]:
|
| 496 |
+
return get_mutable_args_from_schema(op._schema)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def do_auto_functionalize(
|
| 500 |
+
mode: "torch._subclasses.functional_tensor.FunctionalTensorMode",
|
| 501 |
+
op: OpOverload,
|
| 502 |
+
args: tuple[Any, ...],
|
| 503 |
+
kwargs: dict[str, Any],
|
| 504 |
+
) -> Any:
|
| 505 |
+
"""Functionalizes a call to op(*args, **kwargs) by emitting a call to
|
| 506 |
+
`outs = auto_functionalized(op, normalized_kwargs)`
|
| 507 |
+
and replacing the mutated (args, kwargs) with the corresponding outputs.
|
| 508 |
+
|
| 509 |
+
The normalized_kwargs are just the (args, kwargs), but all in kwarg form.
|
| 510 |
+
This makes handling easier for the auto_functionalized HOP.
|
| 511 |
+
"""
|
| 512 |
+
from torch._subclasses.functional_tensor import PythonFunctionalizeAPI
|
| 513 |
+
|
| 514 |
+
ctx = PythonFunctionalizeAPI(mode=mode)
|
| 515 |
+
|
| 516 |
+
# All of the (args, kwargs), but all as kwargs. The names for the
|
| 517 |
+
# args come from the schema. This makes it easier for us to work with them.
|
| 518 |
+
normalized_kwargs = {}
|
| 519 |
+
schema = op._schema
|
| 520 |
+
for idx, arg in enumerate(schema.arguments):
|
| 521 |
+
# NB: torch_dispatch kwargs are the args defined as kwarg-only in the schema
|
| 522 |
+
if arg.name in kwargs:
|
| 523 |
+
normalized_kwargs[arg.name] = kwargs[arg.name]
|
| 524 |
+
elif idx < len(args):
|
| 525 |
+
# if its out of bounds we don't need to do anything
|
| 526 |
+
# as it means the optional arg was passed with its default
|
| 527 |
+
# value
|
| 528 |
+
normalized_kwargs[arg.name] = args[idx]
|
| 529 |
+
else:
|
| 530 |
+
normalized_kwargs[arg.name] = arg.default_value
|
| 531 |
+
|
| 532 |
+
unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type]
|
| 533 |
+
if "self" in unwrapped_kwargs or "self_" in unwrapped_kwargs:
|
| 534 |
+
warnings.warn(
|
| 535 |
+
"Using `self` or `self_` as an argument in the definition of custom ops may lead to ambiguous parsing. "
|
| 536 |
+
"Please consider using a different name for this argument to avoid potential issues.",
|
| 537 |
+
stacklevel=2,
|
| 538 |
+
)
|
| 539 |
+
with ctx.redispatch_to_next():
|
| 540 |
+
unwrapped_outs = auto_functionalized(
|
| 541 |
+
op,
|
| 542 |
+
**unwrapped_kwargs, # type: ignore[arg-type]
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
# List of the name of args that get mutated (according to the schema)
|
| 546 |
+
mutable_args_names, _ = get_mutable_args(op)
|
| 547 |
+
|
| 548 |
+
unwrapped_actual_out: Any | tuple[Any] = unwrapped_outs[: -len(mutable_args_names)]
|
| 549 |
+
unwrapped_mutable_out = unwrapped_outs[-len(mutable_args_names) :]
|
| 550 |
+
|
| 551 |
+
if len(op._schema.returns) == 0:
|
| 552 |
+
if unwrapped_actual_out[0] is not None:
|
| 553 |
+
raise AssertionError(
|
| 554 |
+
f"Expected None for op with no returns, got {unwrapped_actual_out[0]}"
|
| 555 |
+
)
|
| 556 |
+
unwrapped_actual_out = None
|
| 557 |
+
elif len(op._schema.returns) == 1:
|
| 558 |
+
if len(unwrapped_actual_out) != 1:
|
| 559 |
+
raise AssertionError(f"Expected 1 output, got {len(unwrapped_actual_out)}")
|
| 560 |
+
unwrapped_actual_out = unwrapped_actual_out[0]
|
| 561 |
+
else:
|
| 562 |
+
if len(unwrapped_actual_out) != len(op._schema.returns):
|
| 563 |
+
raise AssertionError(
|
| 564 |
+
f"Expected {len(op._schema.returns)} outputs, got {len(unwrapped_actual_out)}"
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
for name, unwrapped_out in zip(mutable_args_names, unwrapped_mutable_out):
|
| 568 |
+
# Can be None if input was `Tensor(a!)?`
|
| 569 |
+
if unwrapped_out is None:
|
| 570 |
+
continue
|
| 571 |
+
|
| 572 |
+
# We only handle Tensor or List[Tensor] here for now.
|
| 573 |
+
def sync_update(o, orig_arg):
|
| 574 |
+
ctx.replace(orig_arg, o)
|
| 575 |
+
ctx.commit_update(orig_arg)
|
| 576 |
+
ctx.sync(orig_arg)
|
| 577 |
+
|
| 578 |
+
orig_arg = normalized_kwargs[name]
|
| 579 |
+
|
| 580 |
+
if isinstance(unwrapped_out, torch.Tensor):
|
| 581 |
+
sync_update(unwrapped_out, orig_arg)
|
| 582 |
+
elif isinstance(unwrapped_out, list) and all(
|
| 583 |
+
isinstance(o, torch.Tensor) for o in unwrapped_out
|
| 584 |
+
):
|
| 585 |
+
if len(orig_arg) != len(unwrapped_out):
|
| 586 |
+
raise AssertionError(
|
| 587 |
+
f"orig_arg length ({len(orig_arg)}) != unwrapped_out length ({len(unwrapped_out)})"
|
| 588 |
+
)
|
| 589 |
+
for orig_a, o in zip(orig_arg, unwrapped_out):
|
| 590 |
+
sync_update(o, orig_a)
|
| 591 |
+
else:
|
| 592 |
+
raise RuntimeError(
|
| 593 |
+
f"unsupported type for auto-functionalization: {unwrapped_out}"
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
return ctx.wrap_tensors(unwrapped_actual_out) # type: ignore[arg-type]
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
# Wrapper for GraphModule that applies functionalization during execution to enable
|
| 600 |
+
# epilogue graph inlining and better fusion opportunities in subgraphs
|
| 601 |
+
# When tracing this wrapper, we'll get a graph module with epilogue.
|
| 602 |
+
#
|
| 603 |
+
# We want to hash it according to the original graph module, so that when we go
|
| 604 |
+
# from Functional mode -> fake mode for multiple invoke_subgraph calls that share,
|
| 605 |
+
# the same inner graph module, we can hit the cache.
|
| 606 |
+
class FunctionalCallableWithEpilogue:
|
| 607 |
+
def __init__(self, orig_callable: Callable):
|
| 608 |
+
self.orig_callable = orig_callable
|
| 609 |
+
# Propagate so callers pass inputs as a list, enabling input deallocation.
|
| 610 |
+
self._boxed_call = getattr(orig_callable, "_boxed_call", False)
|
| 611 |
+
|
| 612 |
+
def __call__(self, *args, **kwargs):
|
| 613 |
+
# Functionalize to inline the epilogue graph (copy_ ops) for better fusion.
|
| 614 |
+
functionalized = torch.func.functionalize(self.orig_callable)
|
| 615 |
+
if self._boxed_call:
|
| 616 |
+
# Not all callers respect _boxed_call (e.g. reenter_make_fx
|
| 617 |
+
# always calls f(*args)). Detect which convention was used.
|
| 618 |
+
if len(args) == 1 and isinstance(args[0], list):
|
| 619 |
+
return tuple(functionalized(args[0]))
|
| 620 |
+
return tuple(functionalized(list(args)))
|
| 621 |
+
return tuple(functionalized(*args, **kwargs))
|
| 622 |
+
|
| 623 |
+
def __hash__(self):
|
| 624 |
+
return id(self.orig_callable)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def do_auto_functionalize_v2(
|
| 628 |
+
mode: "torch._subclasses.functional_tensor.FunctionalTensorMode",
|
| 629 |
+
op: OpOverload | HopInstance,
|
| 630 |
+
args: tuple[Any, ...],
|
| 631 |
+
kwargs: dict[str, Any],
|
| 632 |
+
) -> Any:
|
| 633 |
+
from torch._subclasses.functional_tensor import PythonFunctionalizeAPI
|
| 634 |
+
|
| 635 |
+
ctx = PythonFunctionalizeAPI(mode=mode)
|
| 636 |
+
|
| 637 |
+
# All of the (args, kwargs), but all as kwargs. The names for the
|
| 638 |
+
# args come from the schema. This makes it easier for us to work with them.
|
| 639 |
+
normalized_kwargs = {}
|
| 640 |
+
|
| 641 |
+
schema = op._schema
|
| 642 |
+
# pyrefly: ignore [bad-assignment]
|
| 643 |
+
op = op._op if isinstance(op, HopInstance) else op
|
| 644 |
+
if not isinstance(op, get_args(_MutableOpType)):
|
| 645 |
+
raise AssertionError(f"Expected _MutableOpType, got {type(op)}")
|
| 646 |
+
|
| 647 |
+
subgraph_arg_names = {
|
| 648 |
+
arg_info.name
|
| 649 |
+
for arg_info in schema.arguments
|
| 650 |
+
if isinstance(arg_info.type, torch._C.AnyType)
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
def _maybe_functionalize(name: str, arg: Any) -> Any:
|
| 654 |
+
if name in subgraph_arg_names and callable(arg):
|
| 655 |
+
return FunctionalCallableWithEpilogue(arg)
|
| 656 |
+
return arg
|
| 657 |
+
|
| 658 |
+
args = tuple(
|
| 659 |
+
_maybe_functionalize(schema.arguments[i].name, a)
|
| 660 |
+
if i < len(schema.arguments)
|
| 661 |
+
else a
|
| 662 |
+
for i, a in enumerate(args)
|
| 663 |
+
)
|
| 664 |
+
kwargs = {k: _maybe_functionalize(k, v) for k, v in kwargs.items()}
|
| 665 |
+
|
| 666 |
+
for idx, arg in enumerate(schema.arguments):
|
| 667 |
+
# NB: torch_dispatch kwargs are the args defined as kwarg-only in the schema
|
| 668 |
+
if arg.name in kwargs:
|
| 669 |
+
normalized_kwargs[arg.name] = kwargs[arg.name]
|
| 670 |
+
elif idx < len(args):
|
| 671 |
+
# if its out of bounds we don't need to do anything
|
| 672 |
+
# as it means the optional arg was passed with its default
|
| 673 |
+
# value
|
| 674 |
+
normalized_kwargs[arg.name] = args[idx]
|
| 675 |
+
else:
|
| 676 |
+
normalized_kwargs[arg.name] = arg.default_value
|
| 677 |
+
|
| 678 |
+
# List of the name of args that get mutated (according to the schema)
|
| 679 |
+
mutable_args_names, mutable_args_types = get_mutable_args_from_schema(schema)
|
| 680 |
+
|
| 681 |
+
# A list of all bases of mutable args without duplication
|
| 682 |
+
all_bases = []
|
| 683 |
+
all_bases_addresses: list[int] = []
|
| 684 |
+
|
| 685 |
+
# Map arg_name to the index of its base in all_bases.
|
| 686 |
+
arg_to_base_index: dict[str, Any] = {}
|
| 687 |
+
|
| 688 |
+
def update_dict(tensor, arg_name, index=None):
|
| 689 |
+
base = tensor if get_base(tensor) is None else get_base(tensor)
|
| 690 |
+
|
| 691 |
+
def set_result(base_index):
|
| 692 |
+
if index is None:
|
| 693 |
+
arg_to_base_index[arg_name] = base_index
|
| 694 |
+
else:
|
| 695 |
+
arg_to_base_index[arg_name][index] = base_index
|
| 696 |
+
|
| 697 |
+
if not all_bases_addresses.__contains__(base._cdata):
|
| 698 |
+
all_bases_addresses.append(base._cdata)
|
| 699 |
+
all_bases.append(base)
|
| 700 |
+
set_result(len(all_bases) - 1)
|
| 701 |
+
else:
|
| 702 |
+
set_result(all_bases_addresses.index(base._cdata))
|
| 703 |
+
|
| 704 |
+
for arg_name in mutable_args_names:
|
| 705 |
+
arg = normalized_kwargs[arg_name]
|
| 706 |
+
if arg is None:
|
| 707 |
+
continue
|
| 708 |
+
|
| 709 |
+
if isinstance(arg, list):
|
| 710 |
+
arg_to_base_index[arg_name] = {}
|
| 711 |
+
for i, tensor in enumerate(arg):
|
| 712 |
+
if tensor is None:
|
| 713 |
+
arg_to_base_index[arg_name].append(None)
|
| 714 |
+
continue
|
| 715 |
+
|
| 716 |
+
update_dict(tensor, arg_name, i)
|
| 717 |
+
|
| 718 |
+
else:
|
| 719 |
+
update_dict(arg, arg_name)
|
| 720 |
+
|
| 721 |
+
# add view_meta for each args into unwrapped_kwargs.
|
| 722 |
+
write_view_information_to_args(
|
| 723 |
+
mutable_args_names,
|
| 724 |
+
mutable_args_types,
|
| 725 |
+
normalized_kwargs,
|
| 726 |
+
arg_to_base_index,
|
| 727 |
+
)
|
| 728 |
+
|
| 729 |
+
# remove mutated args from the kwargs (its a function of _all_bases now)
|
| 730 |
+
for arg_name in mutable_args_names:
|
| 731 |
+
del normalized_kwargs[arg_name] # type: ignore[arg-type]
|
| 732 |
+
|
| 733 |
+
unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type]
|
| 734 |
+
if "self" in unwrapped_kwargs or "self_" in unwrapped_kwargs:
|
| 735 |
+
warnings.warn(
|
| 736 |
+
"Using `self` or `self_` as an argument in the definition of custom ops may lead to ambiguous parsing. "
|
| 737 |
+
"Please consider using a different name for this argument to avoid potential issues.",
|
| 738 |
+
stacklevel=2,
|
| 739 |
+
)
|
| 740 |
+
all_basis_unwrapped = ctx.unwrap_tensors(all_bases)
|
| 741 |
+
|
| 742 |
+
if "_all_bases" in unwrapped_kwargs:
|
| 743 |
+
raise AssertionError(f"_all_bases already in unwrapped_kwargs for {op}")
|
| 744 |
+
auto_func_kwargs = dict(unwrapped_kwargs, _all_bases=all_basis_unwrapped)
|
| 745 |
+
if isinstance(op, HigherOrderOperator):
|
| 746 |
+
if "_ops_schema" in unwrapped_kwargs:
|
| 747 |
+
raise AssertionError(f"_ops_schema already in unwrapped_kwargs for {op}")
|
| 748 |
+
# We pass in the tree_spec of tree_flatten(SchemaHolder) to make it proxable
|
| 749 |
+
auto_func_kwargs.update(
|
| 750 |
+
{"_op_schema": pytree.tree_flatten(SchemaHolder(schema))[1]}
|
| 751 |
+
)
|
| 752 |
+
|
| 753 |
+
with ctx.redispatch_to_next():
|
| 754 |
+
unwrapped_outs = auto_functionalized_v2(
|
| 755 |
+
op,
|
| 756 |
+
**auto_func_kwargs, # type: ignore[arg-type]
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
unwrapped_actual_out: Any | tuple[Any] = (
|
| 760 |
+
unwrapped_outs if len(all_bases) == 0 else unwrapped_outs[: -len(all_bases)]
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
unwrapped_mutable_out = (
|
| 764 |
+
[] if len(all_bases) == 0 else unwrapped_outs[-len(all_bases) :]
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
if isinstance(op, HigherOrderOperator):
|
| 768 |
+
if len(schema.returns) <= 0:
|
| 769 |
+
raise AssertionError(
|
| 770 |
+
f"hop is expected to return at least one output {schema}."
|
| 771 |
+
)
|
| 772 |
+
if len(unwrapped_actual_out) != len(schema.returns):
|
| 773 |
+
raise AssertionError(
|
| 774 |
+
f"Expected {len(schema.returns)} outputs, got {len(unwrapped_actual_out)}"
|
| 775 |
+
)
|
| 776 |
+
else:
|
| 777 |
+
if len(schema.returns) == 0:
|
| 778 |
+
if unwrapped_actual_out[0] is not None:
|
| 779 |
+
raise AssertionError(
|
| 780 |
+
f"Expected None for op with no returns, got {unwrapped_actual_out[0]}"
|
| 781 |
+
)
|
| 782 |
+
unwrapped_actual_out = None
|
| 783 |
+
elif len(schema.returns) == 1:
|
| 784 |
+
if len(unwrapped_actual_out) != 1:
|
| 785 |
+
raise AssertionError(
|
| 786 |
+
f"Expected 1 output, got {len(unwrapped_actual_out)}"
|
| 787 |
+
)
|
| 788 |
+
unwrapped_actual_out = unwrapped_actual_out[0]
|
| 789 |
+
else:
|
| 790 |
+
if len(unwrapped_actual_out) != len(schema.returns):
|
| 791 |
+
raise AssertionError(
|
| 792 |
+
f"Expected {len(schema.returns)} outputs, got {len(unwrapped_actual_out)}"
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
for orig_arg, unwrapped_out in zip(all_bases, unwrapped_mutable_out):
|
| 796 |
+
# Can be None if input was `Tensor(a!)?`
|
| 797 |
+
if unwrapped_out is None:
|
| 798 |
+
continue
|
| 799 |
+
|
| 800 |
+
# We only handle Tensor or List[Tensor] here for now.
|
| 801 |
+
def sync_update(o, orig_arg):
|
| 802 |
+
ctx.replace(orig_arg, o)
|
| 803 |
+
ctx.commit_update(orig_arg)
|
| 804 |
+
ctx.sync(orig_arg)
|
| 805 |
+
|
| 806 |
+
if isinstance(unwrapped_out, torch.Tensor):
|
| 807 |
+
sync_update(unwrapped_out, orig_arg)
|
| 808 |
+
elif isinstance(unwrapped_out, list) and all(
|
| 809 |
+
isinstance(o, torch.Tensor) for o in unwrapped_out
|
| 810 |
+
):
|
| 811 |
+
if len(orig_arg) != len(unwrapped_out):
|
| 812 |
+
raise AssertionError(
|
| 813 |
+
f"orig_arg length ({len(orig_arg)}) != unwrapped_out length ({len(unwrapped_out)})"
|
| 814 |
+
)
|
| 815 |
+
for orig_a, o in zip(orig_arg, unwrapped_out):
|
| 816 |
+
sync_update(o, orig_a)
|
| 817 |
+
else:
|
| 818 |
+
raise RuntimeError(
|
| 819 |
+
f"unsupported type for auto-functionalization: {unwrapped_out}"
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
return ctx.wrap_tensors(unwrapped_actual_out) # type: ignore[arg-type]
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
# auto_functionalize functions
|
| 826 |
+
@auto_functionalized.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 827 |
+
def auto_functionalized_dense(
|
| 828 |
+
_mutable_op: OpOverload,
|
| 829 |
+
_only_clone_these_tensors: tuple[str, ...] | None = None,
|
| 830 |
+
**kwargs: Any,
|
| 831 |
+
) -> tuple[Any, tuple[Tensor, ...]]:
|
| 832 |
+
new_kwargs = dict(**kwargs)
|
| 833 |
+
result = []
|
| 834 |
+
|
| 835 |
+
_mutable_args_names, _ = get_mutable_args(_mutable_op)
|
| 836 |
+
for name in _mutable_args_names:
|
| 837 |
+
if (
|
| 838 |
+
_only_clone_these_tensors is not None
|
| 839 |
+
and name not in _only_clone_these_tensors
|
| 840 |
+
):
|
| 841 |
+
new_kwargs[name] = kwargs[name]
|
| 842 |
+
else:
|
| 843 |
+
new_kwargs[name] = (
|
| 844 |
+
[clone_preserve_strides(x) for x in kwargs[name]]
|
| 845 |
+
if kwargs[name] is not None and isinstance(kwargs[name], list)
|
| 846 |
+
else (
|
| 847 |
+
clone_preserve_strides(kwargs[name])
|
| 848 |
+
if kwargs[name] is not None
|
| 849 |
+
else None
|
| 850 |
+
)
|
| 851 |
+
)
|
| 852 |
+
result.append(new_kwargs[name])
|
| 853 |
+
out = _mutable_op(**new_kwargs)
|
| 854 |
+
|
| 855 |
+
if isinstance(out, tuple):
|
| 856 |
+
return (*out, *result) # type: ignore[return-value]
|
| 857 |
+
else:
|
| 858 |
+
return (out, *result) # type: ignore[return-value]
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
@auto_functionalized.py_impl(FakeTensorMode)
|
| 862 |
+
def auto_functionalized_fake(
|
| 863 |
+
mode,
|
| 864 |
+
_mutable_op: OpOverload,
|
| 865 |
+
**kwargs: Any,
|
| 866 |
+
) -> tuple[Any, tuple[Tensor, ...]]:
|
| 867 |
+
with mode:
|
| 868 |
+
result = auto_functionalized_dense(
|
| 869 |
+
_mutable_op, _only_clone_these_tensors=None, **kwargs
|
| 870 |
+
)
|
| 871 |
+
return result
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
@auto_functionalized.py_impl(ProxyTorchDispatchMode)
|
| 875 |
+
def auto_functionalized_proxy(
|
| 876 |
+
mode,
|
| 877 |
+
_mutable_op: OpOverload,
|
| 878 |
+
**kwargs: Any,
|
| 879 |
+
) -> tuple[Any, tuple[Tensor, ...]]:
|
| 880 |
+
with disable_proxy_modes_tracing():
|
| 881 |
+
out = auto_functionalized(_mutable_op, **kwargs)
|
| 882 |
+
|
| 883 |
+
proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs)
|
| 884 |
+
out_proxy = mode.tracer.create_proxy(
|
| 885 |
+
"call_function",
|
| 886 |
+
auto_functionalized,
|
| 887 |
+
(_mutable_op,),
|
| 888 |
+
proxy_kwargs,
|
| 889 |
+
)
|
| 890 |
+
result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
|
| 891 |
+
return result
|
| 892 |
+
|
| 893 |
+
|
| 894 |
+
@auto_functionalized.py_functionalize_impl
|
| 895 |
+
def auto_functionalized_func(ctx, _mutable_op, **kwargs):
|
| 896 |
+
unwrapped_kwargs = ctx.unwrap_tensors(kwargs)
|
| 897 |
+
with ctx.redispatch_to_next():
|
| 898 |
+
result = auto_functionalized(_mutable_op, **unwrapped_kwargs)
|
| 899 |
+
return ctx.wrap_tensors(result)
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
# auto_functionalized_v2 functions
|
| 903 |
+
@auto_functionalized_v2.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 904 |
+
def auto_functionalized_v2_dense(
|
| 905 |
+
_mutable_op: _MutableOpType,
|
| 906 |
+
_only_clone_these_bases: tuple[int, ...] | None = None,
|
| 907 |
+
**kwargs: Any,
|
| 908 |
+
) -> tuple[Any, tuple[Tensor, ...]]:
|
| 909 |
+
_all_bases: list[Tensor] = kwargs.pop("_all_bases", [])
|
| 910 |
+
if _only_clone_these_bases is None:
|
| 911 |
+
_only_clone_these_bases = tuple(range(len(_all_bases)))
|
| 912 |
+
|
| 913 |
+
if isinstance(_mutable_op, OpOverload):
|
| 914 |
+
schema: torch._C.FunctionSchema = _mutable_op._schema
|
| 915 |
+
else:
|
| 916 |
+
schema = pytree.tree_unflatten([], kwargs.pop("_op_schema")).schema
|
| 917 |
+
|
| 918 |
+
if isinstance(_mutable_op, OpOverload):
|
| 919 |
+
_callable_op: HopInstance | OpOverload = _mutable_op
|
| 920 |
+
else:
|
| 921 |
+
if not isinstance(schema, HopSchema):
|
| 922 |
+
raise AssertionError(f"Expected HopSchema, got {type(schema)}")
|
| 923 |
+
_callable_op = HopInstance(_mutable_op, schema)
|
| 924 |
+
|
| 925 |
+
op_kwargs_new, all_bases_new = _generate_new_op_kwargs_from_bases(
|
| 926 |
+
schema,
|
| 927 |
+
kwargs,
|
| 928 |
+
_all_bases,
|
| 929 |
+
_only_clone_these_bases,
|
| 930 |
+
)
|
| 931 |
+
|
| 932 |
+
out = call_op(
|
| 933 |
+
_callable_op,
|
| 934 |
+
tuple(),
|
| 935 |
+
op_kwargs_new,
|
| 936 |
+
)
|
| 937 |
+
|
| 938 |
+
if isinstance(out, tuple):
|
| 939 |
+
return (*out, *all_bases_new) # type: ignore[return-value]
|
| 940 |
+
else:
|
| 941 |
+
return (out, *all_bases_new) # type: ignore[return-value]
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
def _generate_new_op_kwargs_from_bases(
|
| 945 |
+
schema, kwargs, all_bases, _only_clone_these_bases
|
| 946 |
+
):
|
| 947 |
+
mutable_args_names, mutable_args_types = get_mutable_args_from_schema(schema)
|
| 948 |
+
args_view_info = read_view_information_from_args(
|
| 949 |
+
mutable_args_names, mutable_args_types, kwargs, all_bases
|
| 950 |
+
)
|
| 951 |
+
|
| 952 |
+
def maybe_copy(i, t):
|
| 953 |
+
if t is None:
|
| 954 |
+
return None
|
| 955 |
+
if i in _only_clone_these_bases:
|
| 956 |
+
return clone_preserve_strides(t)
|
| 957 |
+
else:
|
| 958 |
+
return t
|
| 959 |
+
|
| 960 |
+
all_bases_new = [maybe_copy(i, t) for i, t in enumerate(all_bases)]
|
| 961 |
+
|
| 962 |
+
# create new args
|
| 963 |
+
new_kwargs = dict(**kwargs)
|
| 964 |
+
|
| 965 |
+
# re-generate all inputs from all_bases_new using args_view_info and add them to new_kwargs.
|
| 966 |
+
for arg_name in mutable_args_names:
|
| 967 |
+
if args_view_info[arg_name] is None:
|
| 968 |
+
new_kwargs[arg_name] = None
|
| 969 |
+
elif isinstance(args_view_info[arg_name], list):
|
| 970 |
+
new_kwargs[arg_name] = []
|
| 971 |
+
for i, elem in enumerate(args_view_info[arg_name]):
|
| 972 |
+
if elem is None:
|
| 973 |
+
new_kwargs[arg_name].append(None)
|
| 974 |
+
else:
|
| 975 |
+
view_info = args_view_info[arg_name][i]
|
| 976 |
+
new_kwargs[arg_name].append(
|
| 977 |
+
view_info.regenerate_view(all_bases_new)
|
| 978 |
+
)
|
| 979 |
+
else:
|
| 980 |
+
new_kwargs[arg_name] = args_view_info[arg_name].regenerate_view(
|
| 981 |
+
all_bases_new
|
| 982 |
+
)
|
| 983 |
+
|
| 984 |
+
return new_kwargs, all_bases_new
|
| 985 |
+
|
| 986 |
+
|
| 987 |
+
@auto_functionalized_v2.py_impl(FakeTensorMode)
|
| 988 |
+
def auto_functionalized_v2_fake(
|
| 989 |
+
mode,
|
| 990 |
+
_mutable_op: _MutableOpType,
|
| 991 |
+
**kwargs: dict[str, Any],
|
| 992 |
+
) -> tuple[Any, tuple[Tensor, ...]]:
|
| 993 |
+
with mode:
|
| 994 |
+
result = auto_functionalized_v2_dense(
|
| 995 |
+
_mutable_op, _only_clone_these_bases=None, **kwargs
|
| 996 |
+
)
|
| 997 |
+
return result
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
@auto_functionalized_v2.py_impl(ProxyTorchDispatchMode)
|
| 1001 |
+
def auto_functionalized_v2_proxy(
|
| 1002 |
+
mode,
|
| 1003 |
+
_mutable_op: _MutableOpType,
|
| 1004 |
+
**kwargs: Any,
|
| 1005 |
+
) -> tuple[Any, tuple[Tensor, ...]]:
|
| 1006 |
+
if isinstance(_mutable_op, HigherOrderOperator):
|
| 1007 |
+
# Note [materialize callable inputs as graph]
|
| 1008 |
+
# Below code materializes the callable inputs to the hop as graph modules.
|
| 1009 |
+
# kwargs may contain general callables, that are not proxable e.g. FunctionWithNoFreeVars
|
| 1010 |
+
# this could happen when we auto_functionalize the backward of the hop,
|
| 1011 |
+
# where backward fn is a callablle that wraps forward graph module.
|
| 1012 |
+
# This function materialize the callable args according to the schema of the hop.
|
| 1013 |
+
|
| 1014 |
+
# We cannot materialize the callables in kwargs directly because the inputs to callable
|
| 1015 |
+
# vary from hops to hop. To make the materialiation process generic to all hops,
|
| 1016 |
+
# we trace a function that wraps the hop and let each hop itself figure out how to trace
|
| 1017 |
+
# its callable inputs. Then we look at the schema of the traced hop node and replace the
|
| 1018 |
+
# callable in original kwarg with the traced subgraphs.
|
| 1019 |
+
#
|
| 1020 |
+
# Specifically, we first trace a wrapped_fn that calls into the hop. Then we look for the
|
| 1021 |
+
# hop node in the traced graph and graph module inputs to the hop. Finally, we replace the
|
| 1022 |
+
# original kwarg's callable with the graph module.
|
| 1023 |
+
all_bases = kwargs.get("_all_bases", [])
|
| 1024 |
+
_only_clone_these_bases = kwargs.get("_only_clone_these_bases")
|
| 1025 |
+
if _only_clone_these_bases is None:
|
| 1026 |
+
_only_clone_these_bases = tuple(range(len(all_bases)))
|
| 1027 |
+
|
| 1028 |
+
schema = pytree.tree_unflatten([], kwargs.get("_op_schema")).schema # type: ignore[arg-type]
|
| 1029 |
+
new_kwargs, _ = _generate_new_op_kwargs_from_bases(
|
| 1030 |
+
schema,
|
| 1031 |
+
{k: v for k, v in kwargs.items() if k not in ("_all_bases", "_op_schema")},
|
| 1032 |
+
all_bases,
|
| 1033 |
+
_only_clone_these_bases,
|
| 1034 |
+
)
|
| 1035 |
+
|
| 1036 |
+
_, materialized_kwargs = materialize_callable_in_args(
|
| 1037 |
+
HopInstance(_mutable_op, schema), tuple(), new_kwargs
|
| 1038 |
+
)
|
| 1039 |
+
|
| 1040 |
+
# Only replace the callables in kwargs with the materialized subgraphs.
|
| 1041 |
+
# The rest of the kwargs are kept unchanged.
|
| 1042 |
+
subgraph_arg_names = {
|
| 1043 |
+
arg_info.name
|
| 1044 |
+
for arg_info in schema.arguments
|
| 1045 |
+
if isinstance(arg_info.type, torch._C.AnyType)
|
| 1046 |
+
}
|
| 1047 |
+
for k, v in kwargs.items():
|
| 1048 |
+
if k in subgraph_arg_names and callable(v):
|
| 1049 |
+
if k not in materialized_kwargs or not isinstance(
|
| 1050 |
+
materialized_kwargs[k], torch.fx.GraphModule
|
| 1051 |
+
):
|
| 1052 |
+
raise AssertionError(
|
| 1053 |
+
f"Expected {k} to be in materialized_kwargs as a GraphModule"
|
| 1054 |
+
)
|
| 1055 |
+
kwargs[k] = materialized_kwargs[k]
|
| 1056 |
+
|
| 1057 |
+
with disable_proxy_modes_tracing():
|
| 1058 |
+
out = auto_functionalized_v2(_mutable_op, **kwargs)
|
| 1059 |
+
|
| 1060 |
+
proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs)
|
| 1061 |
+
|
| 1062 |
+
if isinstance(_mutable_op, HigherOrderOperator):
|
| 1063 |
+
|
| 1064 |
+
def _maybe_register_subgraph(val: Any):
|
| 1065 |
+
if isinstance(val, torch.fx.GraphModule):
|
| 1066 |
+
_, graph_name = unique_graph_id(
|
| 1067 |
+
mode, prefix="auto_functionalized_subgraph"
|
| 1068 |
+
)
|
| 1069 |
+
mode.tracer.root.register_module(graph_name, val)
|
| 1070 |
+
return val
|
| 1071 |
+
return val
|
| 1072 |
+
|
| 1073 |
+
proxy_kwargs = pytree.tree_map(_maybe_register_subgraph, proxy_kwargs)
|
| 1074 |
+
|
| 1075 |
+
out_proxy = mode.tracer.create_proxy(
|
| 1076 |
+
"call_function",
|
| 1077 |
+
auto_functionalized_v2,
|
| 1078 |
+
(_mutable_op,),
|
| 1079 |
+
proxy_kwargs,
|
| 1080 |
+
)
|
| 1081 |
+
result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
|
| 1082 |
+
return result
|
| 1083 |
+
|
| 1084 |
+
|
| 1085 |
+
@auto_functionalized_v2.py_functionalize_impl
|
| 1086 |
+
def auto_functionalized_v2_func(ctx, _mutable_op, **kwargs):
|
| 1087 |
+
unwrapped_kwargs = ctx.unwrap_tensors(kwargs)
|
| 1088 |
+
with ctx.redispatch_to_next():
|
| 1089 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import abc
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.utils._pytree as pytree
|
| 7 |
+
from torch._C import DispatchKey
|
| 8 |
+
from torch._dispatch.python import suspend_functionalization
|
| 9 |
+
from torch._higher_order_ops.auto_functionalize import FunctionalCallableWithEpilogue
|
| 10 |
+
from torch._higher_order_ops.utils import (
|
| 11 |
+
check_input_alias_and_mutation_return_outputs,
|
| 12 |
+
HopInstance,
|
| 13 |
+
materialize_as_graph,
|
| 14 |
+
reenter_make_fx,
|
| 15 |
+
)
|
| 16 |
+
from torch._ops import HigherOrderOperator
|
| 17 |
+
from torch._subclasses import FakeTensorMode
|
| 18 |
+
from torch._subclasses.functional_tensor import disable_functional_mode
|
| 19 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 20 |
+
disable_proxy_modes_tracing,
|
| 21 |
+
ProxyTorchDispatchMode,
|
| 22 |
+
track_tensor_tree,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class BaseHOP(HigherOrderOperator, abc.ABC):
|
| 27 |
+
"""
|
| 28 |
+
This is the "Base" HOP implementation for a HOP that looks like:
|
| 29 |
+
|
| 30 |
+
call_subgraph_hop(subgraph, *operands, **kwargs)
|
| 31 |
+
|
| 32 |
+
That is:
|
| 33 |
+
1) the HOP stays alive until Inductor
|
| 34 |
+
2) the HOP's semantics are subgraph(*operands)
|
| 35 |
+
3) kwargs may be some config options but aren't passed directly to the subgraph.
|
| 36 |
+
|
| 37 |
+
To use this, please subclass this class and override methods as necessary:
|
| 38 |
+
```
|
| 39 |
+
class InvokeQuant(BaseHOP):
|
| 40 |
+
def __init__(self):
|
| 41 |
+
return super().__init__("invoke_quant")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
invoke_quant = InvokeQuant()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def g(x):
|
| 48 |
+
return x.sin().cos()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@torch.compile(backend="aot_eager")
|
| 52 |
+
def f(x):
|
| 53 |
+
return invoke_quant(g, x, scheme="nf4")
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
NOTE: don't subclass BaseHOP out of tree! That is not allowed. All
|
| 57 |
+
usages must be in tree.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(self, hop_name) -> None:
|
| 61 |
+
super().__init__(hop_name)
|
| 62 |
+
|
| 63 |
+
# Set up the registrations
|
| 64 |
+
# If you want to override any of these, override them in your subclass.
|
| 65 |
+
self.py_autograd_impl(self._call_Autograd)
|
| 66 |
+
self.py_functionalize_impl(self._call_Functionalize)
|
| 67 |
+
self.py_impl(ProxyTorchDispatchMode)(self._call_ProxyTorchDispatchMode)
|
| 68 |
+
self.py_impl(FakeTensorMode)(self._call_FakeTensorMode)
|
| 69 |
+
self.py_impl(DispatchKey.CompositeExplicitAutograd)(
|
| 70 |
+
self._call_CompositeExplicitAutograd
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
def __call__(self, subgraph, *operands, **kwargs):
|
| 74 |
+
if not isinstance(
|
| 75 |
+
subgraph,
|
| 76 |
+
(
|
| 77 |
+
torch.fx.GraphModule,
|
| 78 |
+
FunctionWithNoFreeVars,
|
| 79 |
+
FunctionalCallableWithEpilogue,
|
| 80 |
+
),
|
| 81 |
+
):
|
| 82 |
+
raise RuntimeError(
|
| 83 |
+
f"{self._name}: when calling this API without torch.compile, "
|
| 84 |
+
f"we require that the subgraph be a torch.fx.GraphModule (or "
|
| 85 |
+
f"a function we know doesn't have free variables)."
|
| 86 |
+
)
|
| 87 |
+
# pyrefly: ignore [missing-attribute]
|
| 88 |
+
return super().__call__(subgraph, *operands, **kwargs)
|
| 89 |
+
|
| 90 |
+
def _call_Autograd(self, subgraph, *operands, **kwargs):
|
| 91 |
+
if isinstance(subgraph, torch.fx.GraphModule):
|
| 92 |
+
pass
|
| 93 |
+
|
| 94 |
+
# We assume the subgraph doesn't mutate inputs and there is no aliasing.
|
| 95 |
+
# In the PT2 stack, this is Dynamo's responsibility to figure out.
|
| 96 |
+
return BaseHOPFunction.apply(self, subgraph, kwargs, *operands)
|
| 97 |
+
|
| 98 |
+
def _call_CompositeExplicitAutograd(self, subgraph, *operands, **kwargs):
|
| 99 |
+
from torch.utils._python_dispatch import _get_current_dispatch_mode
|
| 100 |
+
|
| 101 |
+
mode = _get_current_dispatch_mode()
|
| 102 |
+
if mode is not None:
|
| 103 |
+
raise AssertionError("Mode should never be enabled for CPU/CUDA key")
|
| 104 |
+
return subgraph(*operands)
|
| 105 |
+
|
| 106 |
+
def _call_ProxyTorchDispatchMode(self, proxy_mode, subgraph, *operands, **kwargs):
|
| 107 |
+
traced_graph = reenter_make_fx(subgraph)(*operands)
|
| 108 |
+
if not isinstance(proxy_mode.tracer, torch.fx.Tracer):
|
| 109 |
+
raise AssertionError(
|
| 110 |
+
f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}"
|
| 111 |
+
)
|
| 112 |
+
qualname = proxy_mode.tracer.get_fresh_qualname("subgraph")
|
| 113 |
+
proxy_mode.tracer.root.register_module(qualname, traced_graph)
|
| 114 |
+
|
| 115 |
+
node_args = (traced_graph, *operands)
|
| 116 |
+
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) # type: ignore[attr-defined]
|
| 117 |
+
proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, kwargs) # type: ignore[attr-defined]
|
| 118 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 119 |
+
"call_function", self, proxy_args, proxy_kwargs
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
out = self(subgraph, *operands, **kwargs)
|
| 123 |
+
return track_tensor_tree(
|
| 124 |
+
out,
|
| 125 |
+
out_proxy,
|
| 126 |
+
constant=None,
|
| 127 |
+
tracer=proxy_mode.tracer, # type: ignore[arg-type]
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
def _call_FakeTensorMode(self, mode, subgraph, *operands, **kwargs):
|
| 131 |
+
# TODO: this should probably route through FakeTensorMode to reuse caching
|
| 132 |
+
with mode:
|
| 133 |
+
return subgraph(*operands)
|
| 134 |
+
|
| 135 |
+
# NOTE [Support input mutation of hops]
|
| 136 |
+
# To support input mutation, hop's subgraph must be functionalized because many inductor passes are
|
| 137 |
+
# applied to subgraph recursively and only work on functional graph. However, we could inline an
|
| 138 |
+
# epilogue graph (i.e. the copy_) into the subgraph because this is how input mutation
|
| 139 |
+
# is implemented in the top-level graph when no hop is presented. All passes must have been and will be
|
| 140 |
+
# aware of the epilogue graph.
|
| 141 |
+
#
|
| 142 |
+
# Since we've supported input mutation for custom op with auto_functionalized, we share the infra for hops
|
| 143 |
+
# The plan is:
|
| 144 |
+
# 1. In hop's Functionalization key, it calls do_auto_functionalize_v2 if subgraph mutates input
|
| 145 |
+
# 2. In do_auto_functionalize_v2:
|
| 146 |
+
# a. we functionalize the callables in hop's argument. This is to make the subgraphs functional so we
|
| 147 |
+
# could recursively run passes on them. Also the epilogue graph is inlined at the end.
|
| 148 |
+
# b. we call auto_functionalized_v2 and pass in an additional schema in order to properly invoke
|
| 149 |
+
# the hop with normalized kwargs.
|
| 150 |
+
# 3. In inductor, we decompose the auto_functionalized hop by callilng into the dense implementation, which
|
| 151 |
+
# copies the mutated inputs to the hop if necessary and call the hop.
|
| 152 |
+
# After these steps, the rest of the inductor stack knows how to fuse the copy_ in subgraph with other ops.
|
| 153 |
+
def _call_Functionalize(self, ctx, subgraph, *operands, **kwargs):
|
| 154 |
+
from torch._higher_order_ops.auto_functionalize import (
|
| 155 |
+
can_auto_functionalize,
|
| 156 |
+
do_auto_functionalize_v2,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
# invoke_quant has non-proxable argument of type InvokeQuant that
|
| 160 |
+
# we cannot generate schema for.
|
| 161 |
+
if self is not torch.ops.higher_order.invoke_quant_packed:
|
| 162 |
+
hop_instance = HopInstance.create(self, subgraph, *operands, **kwargs)
|
| 163 |
+
if can_auto_functionalize(hop_instance):
|
| 164 |
+
return do_auto_functionalize_v2(
|
| 165 |
+
ctx.mode, hop_instance, (subgraph, *operands), kwargs
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
unwrapped_operands = ctx.unwrap_tensors(operands)
|
| 169 |
+
with ctx.redispatch_to_next():
|
| 170 |
+
# We assume the subgraph doesn't mutate inputs and there is no aliasing.
|
| 171 |
+
# In the PT2 stack, this is Dynamo's responsibility to figure out.
|
| 172 |
+
functionalized_subgraph = FunctionWithNoFreeVars(
|
| 173 |
+
ctx.functionalize(subgraph)
|
| 174 |
+
)
|
| 175 |
+
out = self(functionalized_subgraph, *unwrapped_operands, **kwargs)
|
| 176 |
+
return ctx.wrap_tensors(out)
|
| 177 |
+
|
| 178 |
+
# pyrefly: ignore [bad-override]
|
| 179 |
+
def gen_schema(self, subgraph, *operands, **kwargs):
|
| 180 |
+
from .schema import HopSchemaGenerator
|
| 181 |
+
|
| 182 |
+
subgraph = materialize_as_graph(subgraph, operands)
|
| 183 |
+
(
|
| 184 |
+
inp_inp_alias,
|
| 185 |
+
inp_out_alias,
|
| 186 |
+
out_out_alias,
|
| 187 |
+
mutated_inp_idx,
|
| 188 |
+
output,
|
| 189 |
+
) = check_input_alias_and_mutation_return_outputs(subgraph)
|
| 190 |
+
|
| 191 |
+
if not (
|
| 192 |
+
len(inp_inp_alias) == 0
|
| 193 |
+
and len(inp_out_alias) == 0
|
| 194 |
+
and len(out_out_alias) == 0
|
| 195 |
+
):
|
| 196 |
+
# TODO: turn this into an error.
|
| 197 |
+
# test_foreach_map_backward_binary_foreach_map_addrecip_op fails the alias test.
|
| 198 |
+
import warnings
|
| 199 |
+
|
| 200 |
+
warnings.warn(
|
| 201 |
+
"Aliasing is not supported for HOP subgraph.\n"
|
| 202 |
+
f"{subgraph.print_readable(print_output=False)}\n"
|
| 203 |
+
f"Alias info: inp-inp alias: {inp_inp_alias}, inp-out alias: {inp_out_alias}, out-out alias{out_out_alias}"
|
| 204 |
+
f"This may lead to silent incorrectness.",
|
| 205 |
+
stacklevel=2,
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
schema_gen = HopSchemaGenerator(self)
|
| 209 |
+
schema_gen.add_arg("subgraph", subgraph)
|
| 210 |
+
for idx, arg in enumerate(operands):
|
| 211 |
+
schema_gen.add_arg(f"arg{idx}", arg, is_mutated=idx in mutated_inp_idx)
|
| 212 |
+
|
| 213 |
+
for name, arg in kwargs.items():
|
| 214 |
+
schema_gen.add_arg(name, arg, default_value=arg, kw_only=True)
|
| 215 |
+
|
| 216 |
+
for out in output:
|
| 217 |
+
schema_gen.add_output(out)
|
| 218 |
+
|
| 219 |
+
return schema_gen.gen_schema()
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class BaseHOPFunction(torch.autograd.Function):
|
| 223 |
+
@staticmethod
|
| 224 |
+
# pyrefly: ignore [bad-override]
|
| 225 |
+
def forward(ctx, hop, subgraph, kwargs, *operands):
|
| 226 |
+
ctx.hop = hop
|
| 227 |
+
ctx.operands = operands
|
| 228 |
+
ctx.subgraph = subgraph
|
| 229 |
+
ctx.kwargs = kwargs
|
| 230 |
+
|
| 231 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 232 |
+
return hop(subgraph, *operands, **kwargs)
|
| 233 |
+
|
| 234 |
+
@staticmethod
|
| 235 |
+
def backward(ctx, *grad_outputs):
|
| 236 |
+
subgraph = ctx.subgraph
|
| 237 |
+
operands = ctx.operands
|
| 238 |
+
kwargs = ctx.kwargs
|
| 239 |
+
|
| 240 |
+
# TODO: Something special needs to happen with min cut partitioner
|
| 241 |
+
with (
|
| 242 |
+
suspend_functionalization(),
|
| 243 |
+
disable_functional_mode(),
|
| 244 |
+
torch.enable_grad(),
|
| 245 |
+
):
|
| 246 |
+
with disable_proxy_modes_tracing():
|
| 247 |
+
from .invoke_subgraph import create_fw_bw_graph
|
| 248 |
+
from .utils import _from_fun
|
| 249 |
+
|
| 250 |
+
fw_inputs = pytree.tree_map(_from_fun, operands)
|
| 251 |
+
(
|
| 252 |
+
_,
|
| 253 |
+
joint_graph,
|
| 254 |
+
_,
|
| 255 |
+
) = create_fw_bw_graph(subgraph, fw_inputs, grad_outputs)
|
| 256 |
+
|
| 257 |
+
# The joint graph returns (*grad_inputs, *fwd_outputs).
|
| 258 |
+
# We only need the grad_inputs.
|
| 259 |
+
def bwd_fn(*args):
|
| 260 |
+
operands = args[: -len(grad_outputs)]
|
| 261 |
+
grad_outs = args[-len(grad_outputs) :]
|
| 262 |
+
result = joint_graph(*operands, *grad_outs)
|
| 263 |
+
grad_inputs = result[: -len(grad_outputs)]
|
| 264 |
+
return grad_inputs
|
| 265 |
+
|
| 266 |
+
return (
|
| 267 |
+
None,
|
| 268 |
+
None,
|
| 269 |
+
None,
|
| 270 |
+
*ctx.hop(
|
| 271 |
+
FunctionWithNoFreeVars(bwd_fn), *operands, *grad_outputs, **kwargs
|
| 272 |
+
),
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class FunctionWithNoFreeVars:
|
| 277 |
+
def __init__(self, fn):
|
| 278 |
+
self.fn = fn
|
| 279 |
+
|
| 280 |
+
def __call__(self, *args, **kwargs):
|
| 281 |
+
return self.fn(*args, **kwargs)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/cond.py
ADDED
|
@@ -0,0 +1,793 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
import contextlib
|
| 4 |
+
import functools
|
| 5 |
+
import logging
|
| 6 |
+
import warnings
|
| 7 |
+
from collections.abc import Callable
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.utils._pytree as pytree
|
| 12 |
+
from torch._C import DispatchKey
|
| 13 |
+
from torch._C._functorch import (
|
| 14 |
+
_add_batch_dim,
|
| 15 |
+
get_unwrapped,
|
| 16 |
+
is_batchedtensor,
|
| 17 |
+
maybe_get_bdim,
|
| 18 |
+
)
|
| 19 |
+
from torch._functorch.utils import exposed_in
|
| 20 |
+
from torch._higher_order_ops.utils import (
|
| 21 |
+
_maybe_run_with_interpreter,
|
| 22 |
+
check_input_alias_and_mutation_return_outputs,
|
| 23 |
+
create_bw_fn,
|
| 24 |
+
fill_none_with_masks,
|
| 25 |
+
filter_with_masks,
|
| 26 |
+
materialize_as_graph,
|
| 27 |
+
reenter_make_fx,
|
| 28 |
+
save_values_for_backward,
|
| 29 |
+
saved_values,
|
| 30 |
+
unique_graph_id,
|
| 31 |
+
validate_subgraph_args_types,
|
| 32 |
+
)
|
| 33 |
+
from torch._ops import HigherOrderOperator
|
| 34 |
+
from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
|
| 35 |
+
from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
|
| 36 |
+
from torch.utils._python_dispatch import _get_current_dispatch_mode
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
log = logging.getLogger(__name__)
|
| 40 |
+
|
| 41 |
+
"""
|
| 42 |
+
We're going to define a `cond_op` operation.
|
| 43 |
+
In order to do this, we need implementations for each of the dispatch keys.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class CondOp(HigherOrderOperator):
|
| 48 |
+
def __init__(self):
|
| 49 |
+
super().__init__("cond")
|
| 50 |
+
|
| 51 |
+
def __call__(self, pred, true_fn, false_fn, operands):
|
| 52 |
+
validate_subgraph_args_types(operands)
|
| 53 |
+
# pyrefly: ignore [missing-attribute]
|
| 54 |
+
return super().__call__(pred, true_fn, false_fn, operands)
|
| 55 |
+
|
| 56 |
+
# pyrefly: ignore [bad-override]
|
| 57 |
+
def gen_schema(self, pred, true_fn, false_fn, operands):
|
| 58 |
+
from torch._higher_order_ops.schema import HopSchemaGenerator
|
| 59 |
+
from torch._higher_order_ops.utils import materialize_as_graph
|
| 60 |
+
|
| 61 |
+
then_gm: torch.fx.GraphModule = materialize_as_graph(true_fn, operands)
|
| 62 |
+
else_gm: torch.fx.GraphModule = materialize_as_graph(false_fn, operands)
|
| 63 |
+
(
|
| 64 |
+
_,
|
| 65 |
+
_,
|
| 66 |
+
_,
|
| 67 |
+
then_mutated_inputs,
|
| 68 |
+
then_outputs,
|
| 69 |
+
) = check_input_alias_and_mutation_return_outputs(then_gm)
|
| 70 |
+
(
|
| 71 |
+
_,
|
| 72 |
+
_,
|
| 73 |
+
_,
|
| 74 |
+
else_mutated_inputs,
|
| 75 |
+
else_outputs,
|
| 76 |
+
) = check_input_alias_and_mutation_return_outputs(else_gm)
|
| 77 |
+
mutated_inputs = set(then_mutated_inputs) | set(else_mutated_inputs)
|
| 78 |
+
|
| 79 |
+
schema_gen = HopSchemaGenerator(self)
|
| 80 |
+
schema_gen.add_arg("pred", pred)
|
| 81 |
+
schema_gen.add_arg("true_fn", then_gm)
|
| 82 |
+
schema_gen.add_arg("false_fn", else_gm)
|
| 83 |
+
for idx, arg in enumerate(operands):
|
| 84 |
+
schema_gen.add_arg(f"operand{idx}", arg, is_mutated=idx in mutated_inputs)
|
| 85 |
+
|
| 86 |
+
for out in then_outputs:
|
| 87 |
+
schema_gen.add_output(out)
|
| 88 |
+
schema_gen.add_schema_tree_spec(pred, true_fn, false_fn, operands)
|
| 89 |
+
return schema_gen.gen_schema()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
cond_op = CondOp()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@exposed_in("torch")
|
| 96 |
+
def cond(
|
| 97 |
+
pred: bool | int | float | torch.Tensor,
|
| 98 |
+
true_fn: Callable,
|
| 99 |
+
false_fn: Callable,
|
| 100 |
+
operands: tuple | list = (),
|
| 101 |
+
) -> Any:
|
| 102 |
+
r"""
|
| 103 |
+
Conditionally applies `true_fn` or `false_fn`.
|
| 104 |
+
|
| 105 |
+
.. warning::
|
| 106 |
+
|
| 107 |
+
`torch.cond` is a prototype feature in PyTorch. It has limited support for input and output types.
|
| 108 |
+
Please look forward to a more stable implementation in a future version of PyTorch.
|
| 109 |
+
Read more about feature classification at: https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
|
| 110 |
+
|
| 111 |
+
`cond` is structured control flow operator. That is, it is like a Python if-statement,
|
| 112 |
+
but has restrictions on `true_fn`, `false_fn`, and `operands` that enable it to be
|
| 113 |
+
capturable using torch.compile and torch.export.
|
| 114 |
+
|
| 115 |
+
Assuming the constraints on `cond`'s arguments are met, `cond` is equivalent to the following::
|
| 116 |
+
|
| 117 |
+
def cond(pred, true_branch, false_branch, operands):
|
| 118 |
+
if pred:
|
| 119 |
+
return true_branch(*operands)
|
| 120 |
+
else:
|
| 121 |
+
return false_branch(*operands)
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
pred (Union[bool, torch.Tensor]): A boolean expression or a tensor with one element,
|
| 125 |
+
indicating which branch function to apply.
|
| 126 |
+
|
| 127 |
+
true_fn (Callable): A callable function (a -> b) that is within the
|
| 128 |
+
scope that is being traced.
|
| 129 |
+
|
| 130 |
+
false_fn (Callable): A callable function (a -> b) that is within the
|
| 131 |
+
scope that is being traced. The true branch and false branch must
|
| 132 |
+
have consistent input and outputs, meaning the inputs have to be
|
| 133 |
+
the same, and the outputs have to be the same type and shape. Int
|
| 134 |
+
output is also allowed. We'll make the output dynamic by turning it
|
| 135 |
+
into a symint.
|
| 136 |
+
|
| 137 |
+
operands (Tuple of possibly nested dict/list/tuple of torch.Tensor): A tuple of inputs to the
|
| 138 |
+
true/false functions. It can be empty if true_fn/false_fn doesn't require input. Defaults to ().
|
| 139 |
+
|
| 140 |
+
Example::
|
| 141 |
+
|
| 142 |
+
def true_fn(x: torch.Tensor):
|
| 143 |
+
return x.cos()
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def false_fn(x: torch.Tensor):
|
| 147 |
+
return x.sin()
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
return cond(x.shape[0] > 4, true_fn, false_fn, (x,))
|
| 151 |
+
|
| 152 |
+
Restrictions:
|
| 153 |
+
- The conditional statement (aka `pred`) must meet one of the following constraints:
|
| 154 |
+
|
| 155 |
+
- It's a `torch.Tensor` with only one element, and torch.bool dtype
|
| 156 |
+
|
| 157 |
+
- It's a boolean expression, e.g. `x.shape[0] > 10` or `x.dim() > 1 and x.shape[1] > 10`
|
| 158 |
+
|
| 159 |
+
- The branch function (aka `true_fn`/`false_fn`) must meet all of the following constraints:
|
| 160 |
+
|
| 161 |
+
- The function signature must match with operands.
|
| 162 |
+
|
| 163 |
+
- The function must return a tensor with the same metadata, e.g. shape,
|
| 164 |
+
dtype, etc.
|
| 165 |
+
|
| 166 |
+
- The function cannot have in-place mutations on global variables.
|
| 167 |
+
(Note: in-place tensor operations such as `add_` for intermediate results
|
| 168 |
+
are allowed in a branch)
|
| 169 |
+
|
| 170 |
+
- The function can perform in-place mutations on its input tensors during inference (i.e.,
|
| 171 |
+
when `torch.is_grad_enabled()` is False).
|
| 172 |
+
Note: When using `torch.compile()` with a non-constant predicate, the outputs will always
|
| 173 |
+
be new tensors that do not share object identity with the original inputs.
|
| 174 |
+
|
| 175 |
+
Example::
|
| 176 |
+
|
| 177 |
+
def true_fn(x):
|
| 178 |
+
return x.sin_()
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def false_fn(x):
|
| 182 |
+
return x + 1
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def f(x):
|
| 186 |
+
return cond(x.sum() > 0, true_fn, false_fn, (x,))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
x = torch.ones(4)
|
| 190 |
+
with torch.no_grad():
|
| 191 |
+
result = torch.compile(f)(x)
|
| 192 |
+
assert result is not x # result is a new tensor, not the original x
|
| 193 |
+
|
| 194 |
+
"""
|
| 195 |
+
if torch.compiler.is_dynamo_compiling():
|
| 196 |
+
return cond_op(pred, true_fn, false_fn, operands)
|
| 197 |
+
|
| 198 |
+
if isinstance(pred, (bool, int, float)):
|
| 199 |
+
# This is the non-strict export case. Strict export and torch.compile are
|
| 200 |
+
# handled above in dynamo.
|
| 201 |
+
if torch.compiler.is_compiling():
|
| 202 |
+
warnings.warn(
|
| 203 |
+
"Pred is a Python constant. When used with torch.cond, it specializes on one of the branches."
|
| 204 |
+
" If you want torch.cond to preserve two branches, please make the predicate a boolean tensor or a SymBool.",
|
| 205 |
+
UserWarning,
|
| 206 |
+
stacklevel=2,
|
| 207 |
+
)
|
| 208 |
+
# This is the eager case. We can just run the true or false branch.
|
| 209 |
+
if pred:
|
| 210 |
+
return true_fn(*operands)
|
| 211 |
+
else:
|
| 212 |
+
return false_fn(*operands)
|
| 213 |
+
|
| 214 |
+
def _validate_input(pred, true_fn, false_fn, operands):
|
| 215 |
+
if not isinstance(pred, (bool, torch.Tensor, torch.SymBool)):
|
| 216 |
+
raise RuntimeError(f"Expected pred to be bool or tensor, but got {pred}.")
|
| 217 |
+
|
| 218 |
+
if isinstance(pred, torch.Tensor) and pred.numel() != 1:
|
| 219 |
+
raise RuntimeError(
|
| 220 |
+
f"Expected pred to be bool or single-element tensor, but got {pred}."
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
if not callable(true_fn) or not callable(false_fn):
|
| 224 |
+
raise RuntimeError("Expect both branches to be callable.")
|
| 225 |
+
|
| 226 |
+
if not isinstance(operands, (tuple, list)) or pytree.tree_any(
|
| 227 |
+
lambda t: not isinstance(t, torch.Tensor), operands
|
| 228 |
+
):
|
| 229 |
+
raise RuntimeError(
|
| 230 |
+
"Expect operands to be a tuple of possibly nested dict/list/tuple that only "
|
| 231 |
+
f"consists of tensor leaves, but got {operands}."
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
_validate_input(pred, true_fn, false_fn, operands)
|
| 235 |
+
|
| 236 |
+
if not torch._dynamo.is_dynamo_supported():
|
| 237 |
+
raise RuntimeError("torch.cond requires dynamo support.")
|
| 238 |
+
|
| 239 |
+
# Dynamo is expecting a callable with "__code__" attribute.
|
| 240 |
+
# We cannot directly pass cond_op to it. So we wrap it in a dummy function.
|
| 241 |
+
def _cond_op_wrapper(*args, **kwargs):
|
| 242 |
+
return cond_op(*args, **kwargs)
|
| 243 |
+
|
| 244 |
+
from torch._higher_order_ops.utils import _hop_compile_and_call
|
| 245 |
+
|
| 246 |
+
return _hop_compile_and_call(_cond_op_wrapper, (pred, true_fn, false_fn, operands))
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def trace_cond(proxy_mode, func_overload, pred, true_fn, false_fn, operands):
|
| 250 |
+
if not isinstance(operands, (list, tuple)):
|
| 251 |
+
raise AssertionError(
|
| 252 |
+
f"Cond operands must be a list or tuple of tensors and SymInts {operands}"
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
true_graph = reenter_make_fx(true_fn)(*operands)
|
| 256 |
+
false_graph = reenter_make_fx(false_fn)(*operands)
|
| 257 |
+
|
| 258 |
+
true_outs = []
|
| 259 |
+
false_outs = []
|
| 260 |
+
for node in true_graph.graph.nodes:
|
| 261 |
+
if node.op == "output":
|
| 262 |
+
true_outs.extend(node.args)
|
| 263 |
+
|
| 264 |
+
for node in false_graph.graph.nodes:
|
| 265 |
+
if node.op == "output":
|
| 266 |
+
false_outs.extend(node.args)
|
| 267 |
+
|
| 268 |
+
flat_true_outs = pytree.arg_tree_leaves(*true_outs)
|
| 269 |
+
flat_false_outs = pytree.arg_tree_leaves(*false_outs)
|
| 270 |
+
if len(flat_true_outs) != len(flat_false_outs):
|
| 271 |
+
raise torch._dynamo.exc.CondOpArgsMismatchError(
|
| 272 |
+
f"Expected to return same number of outputs but got:"
|
| 273 |
+
f"\n true branch returns {len(flat_true_outs)} item(s)"
|
| 274 |
+
f"\n false branch returns {len(flat_false_outs)} item(s)"
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
i, true_name = unique_graph_id(proxy_mode, prefix="true_graph")
|
| 278 |
+
|
| 279 |
+
false_name = f"false_graph_{i}"
|
| 280 |
+
if hasattr(proxy_mode.tracer.root, false_name):
|
| 281 |
+
raise AssertionError(
|
| 282 |
+
f"proxy_mode.tracer.root already has attribute {false_name}"
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
proxy_mode.tracer.root.register_module(true_name, true_graph)
|
| 286 |
+
proxy_mode.tracer.root.register_module(false_name, false_graph)
|
| 287 |
+
|
| 288 |
+
args = (pred, true_graph, false_graph, operands)
|
| 289 |
+
|
| 290 |
+
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args)
|
| 291 |
+
|
| 292 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 293 |
+
"call_function", func_overload, proxy_args, {}
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
out = func_overload(pred, true_graph, false_graph, operands)
|
| 297 |
+
|
| 298 |
+
return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@cond_op.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 302 |
+
def cond_op_dense(pred, true_fn, false_fn, operands):
|
| 303 |
+
if not all(isinstance(o, (torch.Tensor, int)) for o in operands):
|
| 304 |
+
raise AssertionError(
|
| 305 |
+
f"Dense implementation operands must be a list of tensors and ints {operands}"
|
| 306 |
+
)
|
| 307 |
+
mode = _get_current_dispatch_mode()
|
| 308 |
+
if mode is not None:
|
| 309 |
+
raise AssertionError("Mode should never be enabled for CPU/CUDA key")
|
| 310 |
+
if pred:
|
| 311 |
+
return true_fn(*operands)
|
| 312 |
+
else:
|
| 313 |
+
return false_fn(*operands)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class CondAutogradOp(torch.autograd.Function):
|
| 317 |
+
@staticmethod
|
| 318 |
+
# pyrefly: ignore [bad-override]
|
| 319 |
+
def forward(
|
| 320 |
+
ctx,
|
| 321 |
+
pred,
|
| 322 |
+
true_fn,
|
| 323 |
+
false_fn,
|
| 324 |
+
*operands,
|
| 325 |
+
):
|
| 326 |
+
ctx._pred = pred
|
| 327 |
+
ctx._true_bw_fn = create_bw_fn(
|
| 328 |
+
true_fn,
|
| 329 |
+
operands,
|
| 330 |
+
)
|
| 331 |
+
ctx._false_bw_fn = create_bw_fn(
|
| 332 |
+
false_fn,
|
| 333 |
+
operands,
|
| 334 |
+
)
|
| 335 |
+
# We snapshot the dispatch keys in forward for materializing the
|
| 336 |
+
# the bw_graph in backward.
|
| 337 |
+
ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set()
|
| 338 |
+
ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set()
|
| 339 |
+
save_values_for_backward(ctx, operands)
|
| 340 |
+
|
| 341 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 342 |
+
return cond_op(pred, true_fn, false_fn, operands)
|
| 343 |
+
|
| 344 |
+
@staticmethod
|
| 345 |
+
def backward(ctx, *flat_grads):
|
| 346 |
+
operands = saved_values(ctx)
|
| 347 |
+
args = operands + flat_grads
|
| 348 |
+
# TODO: we need to materialize the bw graphs because dynamo is unable to
|
| 349 |
+
# trace through the joint function when torch.compile torch.autograd.grad.
|
| 350 |
+
|
| 351 |
+
grads_tensor_masks = []
|
| 352 |
+
|
| 353 |
+
def create_fn_remove_none(fn):
|
| 354 |
+
@functools.wraps(fn)
|
| 355 |
+
def wrapped(*args):
|
| 356 |
+
nonlocal grads_tensor_masks
|
| 357 |
+
|
| 358 |
+
true_outputs = fn(*args)
|
| 359 |
+
grads_tensor_masks = [
|
| 360 |
+
bool(isinstance(out, torch.Tensor)) for out in true_outputs
|
| 361 |
+
]
|
| 362 |
+
return filter_with_masks(true_outputs, grads_tensor_masks)
|
| 363 |
+
|
| 364 |
+
return wrapped
|
| 365 |
+
|
| 366 |
+
true_bw_gm = materialize_as_graph(
|
| 367 |
+
create_fn_remove_none(ctx._true_bw_fn),
|
| 368 |
+
args,
|
| 369 |
+
ctx._fw_include_key_set,
|
| 370 |
+
ctx._fw_exclude_key_set,
|
| 371 |
+
force_enable_grad=True,
|
| 372 |
+
)
|
| 373 |
+
false_bw_gm = materialize_as_graph(
|
| 374 |
+
create_fn_remove_none(ctx._false_bw_fn),
|
| 375 |
+
args,
|
| 376 |
+
ctx._fw_include_key_set,
|
| 377 |
+
ctx._fw_exclude_key_set,
|
| 378 |
+
force_enable_grad=True,
|
| 379 |
+
)
|
| 380 |
+
grads = cond_op(
|
| 381 |
+
ctx._pred,
|
| 382 |
+
true_bw_gm,
|
| 383 |
+
false_bw_gm,
|
| 384 |
+
args,
|
| 385 |
+
)
|
| 386 |
+
return None, None, None, *fill_none_with_masks(grads, grads_tensor_masks)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
# Note:
|
| 390 |
+
# As long as one of the tensors in pred or operands requires grad,
|
| 391 |
+
# all the output would require grad with backward fn set to be the CondAutogradOp.
|
| 392 |
+
# This is consistent with autograd.Function's semantic.
|
| 393 |
+
@cond_op.py_autograd_impl
|
| 394 |
+
def cond_autograd(pred, true_fn, false_fn, operands):
|
| 395 |
+
return CondAutogradOp.apply(
|
| 396 |
+
pred,
|
| 397 |
+
true_fn,
|
| 398 |
+
false_fn,
|
| 399 |
+
*operands,
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
@cond_op.py_impl(ProxyTorchDispatchMode)
|
| 404 |
+
def inner(mode, pred, true_fn, false_fn, operands):
|
| 405 |
+
return trace_cond(mode, cond_op, pred, true_fn, false_fn, operands)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
@cond_op.py_impl(FakeTensorMode)
|
| 409 |
+
def cond_fake_tensor_mode(mode, pred, true_fn, false_fn, operands):
|
| 410 |
+
# Ignore here, because if you've gotten here but you're not manually
|
| 411 |
+
# tracing the inner graphs, that means that you intend to reuse the graph
|
| 412 |
+
# directly. Which means the old unbacked symbol bindings are appropriate.
|
| 413 |
+
# This strategy will not work if unbacked symbols can escape.
|
| 414 |
+
ignore_fresh_unbacked = contextlib.nullcontext()
|
| 415 |
+
if mode.shape_env:
|
| 416 |
+
ignore_fresh_unbacked = mode.shape_env.ignore_fresh_unbacked_symbols()
|
| 417 |
+
|
| 418 |
+
with mode, ignore_fresh_unbacked:
|
| 419 |
+
flat_true_outs, true_out_spec = pytree.tree_flatten(true_fn(*operands))
|
| 420 |
+
flat_false_outs, false_out_spec = pytree.tree_flatten(false_fn(*operands))
|
| 421 |
+
if true_out_spec != false_out_spec:
|
| 422 |
+
raise RuntimeError(
|
| 423 |
+
"Unmatched output spec from torch.cond branches: "
|
| 424 |
+
f"true branch tree_spec {true_out_spec} vs false branch tree_spec {false_out_spec}."
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
merged_outs = []
|
| 428 |
+
for true_out, false_out in zip(flat_true_outs, flat_false_outs):
|
| 429 |
+
merged_outs.append(_merge_output(true_out, false_out, mode))
|
| 430 |
+
return pytree.tree_unflatten(merged_outs, true_out_spec)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def check_tensor_meta_match(
|
| 434 |
+
t1: torch.Tensor, t2: torch.Tensor, attr_names: tuple[str, ...], msg_prefix: str
|
| 435 |
+
) -> None:
|
| 436 |
+
def _get_attr_maybe_call(t: torch.Tensor, attr_name: str) -> Any:
|
| 437 |
+
attr = getattr(t, attr_name)
|
| 438 |
+
if callable(attr):
|
| 439 |
+
return attr()
|
| 440 |
+
return attr
|
| 441 |
+
|
| 442 |
+
for attr_name in attr_names:
|
| 443 |
+
lattr = _get_attr_maybe_call(t1, attr_name)
|
| 444 |
+
rattr = _get_attr_maybe_call(t2, attr_name)
|
| 445 |
+
torch._check(
|
| 446 |
+
lattr == rattr,
|
| 447 |
+
lambda: f"{msg_prefix} expected same {attr_name} but got {lattr} and {rattr}.",
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def _merge_output(
|
| 452 |
+
a: torch.Tensor | int | None,
|
| 453 |
+
b: torch.Tensor | int | None,
|
| 454 |
+
mode: FakeTensorMode,
|
| 455 |
+
):
|
| 456 |
+
from torch.fx.experimental.symbolic_shapes import (
|
| 457 |
+
has_free_unbacked_symbols,
|
| 458 |
+
SymIntEqByExpr,
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
if a is None or b is None:
|
| 462 |
+
if not (a is None and b is None):
|
| 463 |
+
raise AssertionError(f"expected both a and b to be None, got a={a}, b={b}")
|
| 464 |
+
return None
|
| 465 |
+
|
| 466 |
+
def min_max(s0, s1):
|
| 467 |
+
def _bound(s0, lower_bound: bool):
|
| 468 |
+
if isinstance(s0, int):
|
| 469 |
+
return s0
|
| 470 |
+
r = mode.shape_env.var_to_range.get( # type: ignore[union-attr]
|
| 471 |
+
s0.node.expr,
|
| 472 |
+
torch.utils._sympy.value_ranges.ValueRanges.unknown(),
|
| 473 |
+
)
|
| 474 |
+
return r.lower if lower_bound else r.upper
|
| 475 |
+
|
| 476 |
+
return min(_bound(s0, True), _bound(s1, True)), max(
|
| 477 |
+
_bound(s0, False), _bound(s1, False)
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
if type(a) is int and type(b) is int:
|
| 481 |
+
if a == b:
|
| 482 |
+
return a
|
| 483 |
+
if mode.shape_env is None:
|
| 484 |
+
raise AssertionError("mode.shape_env is None")
|
| 485 |
+
merged_out = mode.shape_env.create_unbacked_symint()
|
| 486 |
+
mode.shape_env.constrain_symbol_range(merged_out.node.expr, *min_max(a, b))
|
| 487 |
+
return merged_out
|
| 488 |
+
|
| 489 |
+
if not (type(a) is FakeTensor and type(b) is FakeTensor):
|
| 490 |
+
raise AssertionError(
|
| 491 |
+
f"expected both a and b to be FakeTensor, got a={type(a)}, b={type(b)}"
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
# Note: we don't check size, stride because
|
| 495 |
+
# they'll be merged with unbacked symints if they differ.
|
| 496 |
+
_meta_to_check = {
|
| 497 |
+
"dtype",
|
| 498 |
+
"device",
|
| 499 |
+
"layout",
|
| 500 |
+
"dim",
|
| 501 |
+
"is_quantized",
|
| 502 |
+
"is_conj",
|
| 503 |
+
"is_sparse",
|
| 504 |
+
"storage_offset",
|
| 505 |
+
}
|
| 506 |
+
check_tensor_meta_match(
|
| 507 |
+
a,
|
| 508 |
+
b,
|
| 509 |
+
tuple(_meta_to_check),
|
| 510 |
+
msg_prefix="When merging two branches' output in torch.cond, ",
|
| 511 |
+
)
|
| 512 |
+
# NYI
|
| 513 |
+
if a.is_quantized or b.is_quantized:
|
| 514 |
+
raise AssertionError("quantized tensors not yet implemented")
|
| 515 |
+
if a.is_sparse or b.is_sparse:
|
| 516 |
+
raise AssertionError("sparse tensors not yet implemented")
|
| 517 |
+
if a.is_conj() or b.is_conj():
|
| 518 |
+
raise AssertionError("conjugate tensors not yet implemented")
|
| 519 |
+
|
| 520 |
+
"""
|
| 521 |
+
Step 1: create unbacked symints for sizes that are different
|
| 522 |
+
along the same axis. For example:
|
| 523 |
+
a.size is [s0, 4, s0, 5, 4, 5]
|
| 524 |
+
b.size is [s1, 4, s2, 8, 4, 7]
|
| 525 |
+
merged_size will be [u0, 4, u1, u2, 4, u3], where
|
| 526 |
+
u0 has range [min(s0, s1), max(s0, s1)]
|
| 527 |
+
u1 has range [min(s0, s2), max(s0, s2)]
|
| 528 |
+
u2 has range [5, 8]
|
| 529 |
+
u3 has range [5, 7]
|
| 530 |
+
"""
|
| 531 |
+
merged_size: list[int | torch.SymInt] = []
|
| 532 |
+
|
| 533 |
+
def _has_unbacked_symbols(s: int | torch.SymInt) -> bool:
|
| 534 |
+
if isinstance(s, int):
|
| 535 |
+
return False
|
| 536 |
+
else:
|
| 537 |
+
return has_free_unbacked_symbols(s.node.expr)
|
| 538 |
+
|
| 539 |
+
for s0, s1 in zip(a.size(), b.size()):
|
| 540 |
+
# If there are unbacked symbols leaked out of true_branch or false_branch
|
| 541 |
+
# we need to merge them with a new unbacked symbol and track in parent graph.
|
| 542 |
+
if (
|
| 543 |
+
not _has_unbacked_symbols(s0)
|
| 544 |
+
and not _has_unbacked_symbols(s1)
|
| 545 |
+
and SymIntEqByExpr(s0) == SymIntEqByExpr(s1)
|
| 546 |
+
):
|
| 547 |
+
merged_size.append(s0)
|
| 548 |
+
else:
|
| 549 |
+
if mode.shape_env is None:
|
| 550 |
+
raise AssertionError("mode.shape_env is None")
|
| 551 |
+
new_size = mode.shape_env.create_unbacked_symint()
|
| 552 |
+
mode.shape_env.constrain_symbol_range(new_size.node.expr, *min_max(s0, s1))
|
| 553 |
+
merged_size.append(new_size)
|
| 554 |
+
|
| 555 |
+
"""
|
| 556 |
+
This follows the logic in symbolic_shapes._compute_symbolic_stride
|
| 557 |
+
Step 2: Since tensor stride is an accumulative multiplication of the sizes, which is a permutated
|
| 558 |
+
(due to view ops) non-descending sequence.
|
| 559 |
+
|
| 560 |
+
Case 1: No size is 1. In this case, strides have unique values.
|
| 561 |
+
For example, suppose we have a tensor with:
|
| 562 |
+
size [3, 4, 3, 5, 4, 5],
|
| 563 |
+
stride (1200, 300, 1, 12, 3, 60),
|
| 564 |
+
merged_size [u0, u1, u2, u3, u4, u5].
|
| 565 |
+
|
| 566 |
+
We visit the strides in ascending order: 1, 3, 12, 60, 300, 1200. In each step, we check whether
|
| 567 |
+
the current stride is bounded or not and bound next stride by setting.
|
| 568 |
+
stride_expr[next_stride] = current_stride_expr * current_size_expr
|
| 569 |
+
1st round:
|
| 570 |
+
current_stride is 1, current_size is 3, so next_stride is 1 * 3 = 3,
|
| 571 |
+
current_stride_expr is set to 1, current_size_expr is u2, so stride_expr[3] is therefore 1 * u2 = u2
|
| 572 |
+
2nd round:
|
| 573 |
+
current_stride is 3, current_size is 4, so next_stride is 3 * 4 = 12,
|
| 574 |
+
current_stride_expr is stride_expr[3] i.e. u2, current_size_expr is u4, so stride_expr[12] = u2 * u4
|
| 575 |
+
...
|
| 576 |
+
|
| 577 |
+
Case 2: At least one dimension has size 1, which can produce duplicates in strides.
|
| 578 |
+
In this case, theoretically, we cannot uniquely determine the expr of strides because
|
| 579 |
+
the accessing stride_expr with same key in different order causes the final stride expression
|
| 580 |
+
to be different.
|
| 581 |
+
|
| 582 |
+
Suppose we have:
|
| 583 |
+
size: (3, 1)
|
| 584 |
+
stride: (1, 1)
|
| 585 |
+
merged_size: (u0, u1)
|
| 586 |
+
|
| 587 |
+
The stride expr could either be (u1, 1) or (1, u0) depending on whether we start with u1 or u0.
|
| 588 |
+
For this reason, we try to break tie by sorting via descending index so we always get (u1, 1).
|
| 589 |
+
|
| 590 |
+
Note that backend might optimize the strides anyway so this is usually not a problem as long
|
| 591 |
+
as two branches matches. See relevant discussions in https://github.com/pytorch/pytorch/issues/142024.
|
| 592 |
+
|
| 593 |
+
Case 3: Dim has 0 stride. 0 stride doesn't participate in the accumulative multiplication of
|
| 594 |
+
sizes. So they're always treated as constant even if their corresponding size is turned into unbacked symint.
|
| 595 |
+
|
| 596 |
+
Suppose we have:
|
| 597 |
+
size: (3, 3)
|
| 598 |
+
stride: (0, 1)
|
| 599 |
+
merged_size: (u0, u1)
|
| 600 |
+
|
| 601 |
+
The merged stride would be (0, 1)
|
| 602 |
+
"""
|
| 603 |
+
|
| 604 |
+
def _bound_stride(
|
| 605 |
+
a_ex_size: torch.Size,
|
| 606 |
+
b_ex_size: torch.Size,
|
| 607 |
+
a_ex_stride: tuple[int, ...],
|
| 608 |
+
b_ex_stride: tuple[int, ...],
|
| 609 |
+
merged_size: list[int | torch.SymInt],
|
| 610 |
+
) -> list[int | torch.SymInt]:
|
| 611 |
+
from torch._inductor.ir import get_stride_order
|
| 612 |
+
|
| 613 |
+
a_sorted_stride_idx = get_stride_order(a_ex_stride, mode.shape_env)
|
| 614 |
+
b_sorted_stride_idx = get_stride_order(b_ex_stride, mode.shape_env)
|
| 615 |
+
|
| 616 |
+
a_stride_li: list[tuple[int | torch.SymInt, int] | None] = [None] * len(
|
| 617 |
+
a_ex_stride
|
| 618 |
+
)
|
| 619 |
+
b_stride_li: list[tuple[int | torch.SymInt, int] | None] = [None] * len(
|
| 620 |
+
b_ex_stride
|
| 621 |
+
)
|
| 622 |
+
for i, idx in enumerate(a_sorted_stride_idx):
|
| 623 |
+
a_stride_li[idx] = (a_ex_stride[i], -i)
|
| 624 |
+
for i, idx in enumerate(b_sorted_stride_idx):
|
| 625 |
+
b_stride_li[idx] = (b_ex_stride[i], -i)
|
| 626 |
+
|
| 627 |
+
for a_pair, b_pair in zip(a_stride_li, b_stride_li):
|
| 628 |
+
if a_pair is None or b_pair is None:
|
| 629 |
+
raise AssertionError(
|
| 630 |
+
f"expected a_pair and b_pair to be non-None, got a_pair={a_pair}, b_pair={b_pair}"
|
| 631 |
+
)
|
| 632 |
+
_, a_idx = a_pair
|
| 633 |
+
_, b_idx = b_pair
|
| 634 |
+
|
| 635 |
+
if a_idx != b_idx:
|
| 636 |
+
raise RuntimeError(
|
| 637 |
+
f"The sorted order of strides of the two branches' output doesn't match."
|
| 638 |
+
f"this indicates the contiguousness of the two branches are different. "
|
| 639 |
+
f"True branch has stride {a_ex_stride} but false branch has stride {b_ex_stride}."
|
| 640 |
+
f"Consider using contiguous() to make the two branches have the same contiguousness."
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
def _maybe_expr(s: int | torch.SymInt):
|
| 644 |
+
if isinstance(s, int):
|
| 645 |
+
return s
|
| 646 |
+
return s.node.expr
|
| 647 |
+
|
| 648 |
+
a_stride_expr: dict[Any, int | torch.SymInt] = {}
|
| 649 |
+
b_stride_expr: dict[Any, int | torch.SymInt] = {}
|
| 650 |
+
merged_strides: list[int | torch.SymInt] = [None] * len(a_ex_stride) # type: ignore[list-item]
|
| 651 |
+
for a_pair, b_pair in zip(a_stride_li, b_stride_li):
|
| 652 |
+
if a_pair is None or b_pair is None:
|
| 653 |
+
raise AssertionError(
|
| 654 |
+
f"expected a_pair and b_pair to be non-None, got a_pair={a_pair}, b_pair={b_pair}"
|
| 655 |
+
)
|
| 656 |
+
a_val, neg_i = a_pair
|
| 657 |
+
b_val, _ = b_pair
|
| 658 |
+
|
| 659 |
+
i = -neg_i
|
| 660 |
+
if a_val == 0:
|
| 661 |
+
if b_val != 0:
|
| 662 |
+
raise AssertionError(
|
| 663 |
+
f"expected b_val == 0 when a_val == 0, got a_val={a_val}, b_val={b_val}"
|
| 664 |
+
)
|
| 665 |
+
merged_strides[i] = 0
|
| 666 |
+
continue
|
| 667 |
+
|
| 668 |
+
if _maybe_expr(a_val) in a_stride_expr:
|
| 669 |
+
a_expr = a_stride_expr[_maybe_expr(a_val)]
|
| 670 |
+
if b_stride_expr[_maybe_expr(b_val)] != a_expr:
|
| 671 |
+
raise AssertionError(
|
| 672 |
+
f"a_stride_expr:{a_stride_expr}, b_stride_expr:{b_stride_expr}"
|
| 673 |
+
)
|
| 674 |
+
merged_strides[i] = a_expr
|
| 675 |
+
else:
|
| 676 |
+
if a_val == 1:
|
| 677 |
+
if b_val != 1:
|
| 678 |
+
raise AssertionError(
|
| 679 |
+
f"expected b_val == 1 when a_val == 1, got b_val={b_val}"
|
| 680 |
+
)
|
| 681 |
+
a_stride_expr[_maybe_expr(a_val)] = 1
|
| 682 |
+
b_stride_expr[_maybe_expr(b_val)] = 1
|
| 683 |
+
merged_strides[i] = 1
|
| 684 |
+
else:
|
| 685 |
+
# If we cannot find the expr of a_val in a_stride_expr, it means
|
| 686 |
+
# the strides is not a simple accumulative multiplication of sizes.
|
| 687 |
+
# In this case, we cannot determine the expr of strides from the new
|
| 688 |
+
# shapes so we error out and hint users to call contiguous().
|
| 689 |
+
raise RuntimeError(
|
| 690 |
+
f"It seems one of cond's output stride is not a simple accumulative multiplication of sizes. "
|
| 691 |
+
f"This could be because cond returns a slice of a tensor, which is not dense in memory. "
|
| 692 |
+
f"True branch has size {a_ex_size}, stride {a_ex_stride} and false branch has size {b_ex_size} "
|
| 693 |
+
f"stride {b_ex_stride}. Hint: can call t.contiguous(). "
|
| 694 |
+
)
|
| 695 |
+
nxt_merged_stride_expr = merged_strides[i] * merged_size[i]
|
| 696 |
+
a_stride_expr[_maybe_expr(a_val * a_ex_size[i])] = nxt_merged_stride_expr
|
| 697 |
+
b_stride_expr[_maybe_expr(b_val * b_ex_size[i])] = nxt_merged_stride_expr
|
| 698 |
+
return merged_strides
|
| 699 |
+
|
| 700 |
+
merged_stride: list[int | torch.SymInt] = _bound_stride(
|
| 701 |
+
a.size(), b.size(), a.stride(), b.stride(), merged_size
|
| 702 |
+
)
|
| 703 |
+
|
| 704 |
+
with mode:
|
| 705 |
+
return torch.empty_strided(
|
| 706 |
+
merged_size, merged_stride, dtype=a.dtype, device=a.device
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
@cond_op.py_functionalize_impl
|
| 711 |
+
def cond_func(ctx, pred, true_fn, false_fn, inputs):
|
| 712 |
+
from torch._higher_order_ops.auto_functionalize import (
|
| 713 |
+
can_auto_functionalize,
|
| 714 |
+
do_auto_functionalize_v2,
|
| 715 |
+
)
|
| 716 |
+
from torch._higher_order_ops.utils import _check_alias_and_mutation, HopInstance
|
| 717 |
+
|
| 718 |
+
hop_instance = HopInstance.create(cond_op, pred, true_fn, false_fn, inputs)
|
| 719 |
+
# For now, we only support auto-functionalization for cond when using python
|
| 720 |
+
# functionalization mode
|
| 721 |
+
if can_auto_functionalize(hop_instance) and hasattr(ctx, "mode"):
|
| 722 |
+
return do_auto_functionalize_v2(
|
| 723 |
+
ctx.mode,
|
| 724 |
+
hop_instance,
|
| 725 |
+
tuple(pytree.tree_flatten((pred, true_fn, false_fn, inputs))[0]),
|
| 726 |
+
{},
|
| 727 |
+
)
|
| 728 |
+
|
| 729 |
+
unwrapped_inputs = ctx.unwrap_tensors(inputs)
|
| 730 |
+
unwrapped_pred = ctx.unwrap_tensors(pred)
|
| 731 |
+
with ctx.redispatch_to_next():
|
| 732 |
+
functional_true = ctx.functionalize(_maybe_run_with_interpreter(true_fn))
|
| 733 |
+
functional_false = ctx.functionalize(_maybe_run_with_interpreter(false_fn))
|
| 734 |
+
pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
|
| 735 |
+
for branch, branch_name in [(true_fn, "cond_true"), (false_fn, "cond_false")]:
|
| 736 |
+
_check_alias_and_mutation(
|
| 737 |
+
branch, unwrapped_inputs, branch_name, pre_dispatch
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
cond_return = cond_op(
|
| 741 |
+
unwrapped_pred, functional_true, functional_false, unwrapped_inputs
|
| 742 |
+
)
|
| 743 |
+
return ctx.wrap_tensors(cond_return)
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
@cond_op.py_impl(torch._C._functorch.TransformType.Vmap)
|
| 747 |
+
def cond_batch_rule(interpreter, pred, true_fn, false_fn, inputs):
|
| 748 |
+
if not isinstance(inputs, (list, tuple)):
|
| 749 |
+
raise AssertionError(
|
| 750 |
+
f"Cond inputs must be a list or tuple of tensors, got {type(inputs)}"
|
| 751 |
+
)
|
| 752 |
+
if not all(isinstance(i, torch.Tensor) for i in inputs):
|
| 753 |
+
raise AssertionError(
|
| 754 |
+
f"Cond inputs must be a list of tensors, got {[type(i) for i in inputs]}"
|
| 755 |
+
)
|
| 756 |
+
|
| 757 |
+
pred_is_batched = isinstance(pred, torch.Tensor) and is_batchedtensor(pred)
|
| 758 |
+
pred_ = get_unwrapped(pred) if pred_is_batched else pred
|
| 759 |
+
|
| 760 |
+
# unbatched tensors are not vmapped
|
| 761 |
+
tensors, in_dims = zip(
|
| 762 |
+
*[
|
| 763 |
+
(get_unwrapped(t), maybe_get_bdim(t)) if is_batchedtensor(t) else (t, None)
|
| 764 |
+
for t in inputs
|
| 765 |
+
]
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
if pred_is_batched:
|
| 769 |
+
# prepend "pred" and vmap everything
|
| 770 |
+
tensors = (pred_,) + tensors
|
| 771 |
+
in_dims = (0,) + in_dims
|
| 772 |
+
|
| 773 |
+
def fn(p, *args):
|
| 774 |
+
t = true_fn(*args)
|
| 775 |
+
f = false_fn(*args)
|
| 776 |
+
return torch.where(p, t[0], f[0])
|
| 777 |
+
|
| 778 |
+
with interpreter.lower():
|
| 779 |
+
result = torch.vmap(fn, in_dims=in_dims)(*tensors)
|
| 780 |
+
|
| 781 |
+
else:
|
| 782 |
+
# predicate is known at this stage and it is a boolean expression or a
|
| 783 |
+
# tensor with one element.
|
| 784 |
+
true_fn = torch.vmap(true_fn, in_dims=in_dims)
|
| 785 |
+
false_fn = torch.vmap(false_fn, in_dims=in_dims)
|
| 786 |
+
|
| 787 |
+
with interpreter.lower():
|
| 788 |
+
result = cond_op(pred, true_fn, false_fn, tensors)
|
| 789 |
+
|
| 790 |
+
if not isinstance(result, tuple):
|
| 791 |
+
result = (result,)
|
| 792 |
+
lvl = interpreter.level()
|
| 793 |
+
return tuple(_add_batch_dim(r, 0, lvl) for r in result)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/cudagraph_conditional_nodes.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from collections.abc import Generator
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.utils._pytree as pytree
|
| 7 |
+
from torch.utils._python_dispatch import TorchDispatchMode
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class CUDAGraphCaptureControlFlowOpDispatchMode(TorchDispatchMode):
|
| 11 |
+
@classmethod
|
| 12 |
+
def ignore_compile_internals(cls) -> bool:
|
| 13 |
+
return True
|
| 14 |
+
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
) -> None:
|
| 18 |
+
self.supports_higher_order_operators = True
|
| 19 |
+
super().__init__()
|
| 20 |
+
|
| 21 |
+
def __torch_dispatch__(
|
| 22 |
+
self,
|
| 23 |
+
func,
|
| 24 |
+
types,
|
| 25 |
+
args=(),
|
| 26 |
+
kwargs=None,
|
| 27 |
+
):
|
| 28 |
+
if func is torch.ops.higher_order.cond:
|
| 29 |
+
# Re-enter the mode to support nested conditionals
|
| 30 |
+
with self:
|
| 31 |
+
return if_else_node(*args)
|
| 32 |
+
kwargs = {} if kwargs is None else kwargs
|
| 33 |
+
return func(*args, **kwargs)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ControlFlowOpWarmupDispatchMode(TorchDispatchMode):
|
| 37 |
+
"""The purpose of this TodchDispatchMode is to "warm up" both sides of a torch.cond() statement.
|
| 38 |
+
|
| 39 |
+
For data-dependent control flow code, only one side will be
|
| 40 |
+
executed. Therefore, it is not safe to stream capture a
|
| 41 |
+
torch.cond() statement naively, since we don't have a guarantee
|
| 42 |
+
that all ops will have been "warmed up". The clever workaround is
|
| 43 |
+
to use a "relaxed" stream capture whose final cuda graph we throw
|
| 44 |
+
away. This works because stream capture does not actually execute
|
| 45 |
+
any GPU code, and because true_fn and false_fn are both fxgraphs,
|
| 46 |
+
which do not have any CPU side effects.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
@classmethod
|
| 50 |
+
def ignore_compile_internals(cls) -> bool:
|
| 51 |
+
return True
|
| 52 |
+
|
| 53 |
+
def __init__(
|
| 54 |
+
self,
|
| 55 |
+
) -> None:
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.supports_higher_order_operators = True
|
| 58 |
+
self.capture_stream = torch.cuda.Stream()
|
| 59 |
+
|
| 60 |
+
def __torch_dispatch__(
|
| 61 |
+
self,
|
| 62 |
+
func,
|
| 63 |
+
types,
|
| 64 |
+
args=(),
|
| 65 |
+
kwargs=None,
|
| 66 |
+
):
|
| 67 |
+
kwargs = {} if kwargs is None else kwargs
|
| 68 |
+
|
| 69 |
+
# Warm up both sides of this torch.cond()
|
| 70 |
+
if func is torch.ops.higher_order.cond:
|
| 71 |
+
if torch.cuda.is_current_stream_capturing():
|
| 72 |
+
# This is a call to torch.cond() nested within another
|
| 73 |
+
# torch.cond() function.
|
| 74 |
+
with self:
|
| 75 |
+
# We re-enter the mode in case of nested calls to torch.cond()
|
| 76 |
+
return if_else_node(*args)
|
| 77 |
+
else:
|
| 78 |
+
with (
|
| 79 |
+
torch.cuda.graph(
|
| 80 |
+
torch.cuda.CUDAGraph(),
|
| 81 |
+
pool=None,
|
| 82 |
+
stream=self.capture_stream,
|
| 83 |
+
capture_error_mode="relaxed",
|
| 84 |
+
),
|
| 85 |
+
self,
|
| 86 |
+
):
|
| 87 |
+
if_else_node(*args)
|
| 88 |
+
|
| 89 |
+
return func(*args, **kwargs)
|
| 90 |
+
else:
|
| 91 |
+
return func(*args, **kwargs)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@contextmanager
|
| 95 |
+
def _if_body(pred: torch.Tensor) -> Generator[None, None, None]:
|
| 96 |
+
current_cuda_graph = torch.cuda.CUDAGraph.get_currently_capturing_graph()
|
| 97 |
+
current_cuda_graph.begin_capture_to_if_node(pred)
|
| 98 |
+
try:
|
| 99 |
+
yield
|
| 100 |
+
finally:
|
| 101 |
+
current_cuda_graph.end_capture_to_conditional_node()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def if_else_node(pred: torch.Tensor, true_fn, false_fn, operands):
|
| 105 |
+
if not pred.is_cuda:
|
| 106 |
+
raise ValueError(
|
| 107 |
+
"Conditions must be on a cuda device to use conditional node in cuda graphs"
|
| 108 |
+
)
|
| 109 |
+
# if-else is not supported until CUDA 12.8. Therefore, we use two
|
| 110 |
+
# if conditions, where one evaluates !pred
|
| 111 |
+
outs = []
|
| 112 |
+
|
| 113 |
+
for lazy_pred, fn in [
|
| 114 |
+
(lambda: pred, true_fn),
|
| 115 |
+
(lambda: torch.logical_not(pred), false_fn),
|
| 116 |
+
]:
|
| 117 |
+
with _if_body(lazy_pred()):
|
| 118 |
+
outs.append(fn(*operands))
|
| 119 |
+
|
| 120 |
+
# The output of the else branch gets copied into the
|
| 121 |
+
# output of the if branch. This is done because the rest
|
| 122 |
+
# of the cudagraph after the conditional node has fixed
|
| 123 |
+
# inputs, so we need to merge the two outputs into a
|
| 124 |
+
# single output.
|
| 125 |
+
if len(outs) == 2:
|
| 126 |
+
for if_out, else_out in zip(
|
| 127 |
+
pytree.tree_iter(outs[0]), pytree.tree_iter(outs[1])
|
| 128 |
+
):
|
| 129 |
+
if_out.copy_(else_out)
|
| 130 |
+
return outs[0]
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/effects.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from typing import Any, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.utils._pytree as pytree
|
| 6 |
+
from torch._C import DispatchKey
|
| 7 |
+
from torch._higher_order_ops.invoke_leaf_function import invoke_leaf_function
|
| 8 |
+
from torch._higher_order_ops.print import print as hop_print
|
| 9 |
+
from torch._higher_order_ops.schema import HopSchema
|
| 10 |
+
from torch._higher_order_ops.torchbind import call_torchbind
|
| 11 |
+
from torch._library.custom_ops import CustomOpDef
|
| 12 |
+
from torch._library.effects import EffectType
|
| 13 |
+
from torch._library.utils import RegistrationHandle
|
| 14 |
+
from torch._ops import HigherOrderOperator
|
| 15 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 16 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 17 |
+
disable_proxy_modes_tracing,
|
| 18 |
+
ProxyTorchDispatchMode,
|
| 19 |
+
track_tensor_tree,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_op_identifier = Union[
|
| 24 |
+
str,
|
| 25 |
+
"torch._ops.OpOverload",
|
| 26 |
+
"torch._library.custom_ops.CustomOpDef",
|
| 27 |
+
"torch._ops.HigherOrderOperator",
|
| 28 |
+
]
|
| 29 |
+
OpType = Union["torch._ops.HigherOrderOperator", "torch._ops.OpOverload"]
|
| 30 |
+
|
| 31 |
+
_EffectType = EffectType
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _get_op_qualname(op: _op_identifier) -> str:
|
| 35 |
+
"""Convert an op identifier to a qualified string key."""
|
| 36 |
+
if isinstance(op, torch._ops.OpOverload):
|
| 37 |
+
return op._name
|
| 38 |
+
elif isinstance(op, torch._ops.HigherOrderOperator):
|
| 39 |
+
return f"{op.namespace}::{op.name()}"
|
| 40 |
+
elif isinstance(op, CustomOpDef):
|
| 41 |
+
return op._qualname
|
| 42 |
+
elif isinstance(op, str):
|
| 43 |
+
return op
|
| 44 |
+
|
| 45 |
+
raise ValueError(f"Invalid operator input {op}")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _register_effectful_op(
|
| 49 |
+
op: _op_identifier, effect: EffectType | None
|
| 50 |
+
) -> RegistrationHandle:
|
| 51 |
+
qualname = _get_op_qualname(op)
|
| 52 |
+
entry = torch._library.simple_registry.singleton.find(qualname)
|
| 53 |
+
handle = entry.effect.register(effect)
|
| 54 |
+
return handle
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _get_effect(op: _op_identifier) -> _EffectType | None:
|
| 58 |
+
qualname = _get_op_qualname(op)
|
| 59 |
+
entry = torch._library.simple_registry.singleton.find(qualname)
|
| 60 |
+
return entry.effect.effect
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
_register_effectful_op("aten::_print", _EffectType.ORDERED)
|
| 64 |
+
_register_effectful_op("profiler::_record_function_exit._RecordFunction", None)
|
| 65 |
+
_register_effectful_op(call_torchbind, _EffectType.ORDERED)
|
| 66 |
+
_register_effectful_op(hop_print, _EffectType.ORDERED)
|
| 67 |
+
_register_effectful_op(invoke_leaf_function, _EffectType.ORDERED)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class WithEffects(HigherOrderOperator):
|
| 71 |
+
"""
|
| 72 |
+
with_effects(token, op, args, kwargs) -> (new_token, op_results)
|
| 73 |
+
|
| 74 |
+
This HOP helps ensure ordering between side effectful ops like prints or ops
|
| 75 |
+
using torchbind objects. This is needed to ensure a traced graph from
|
| 76 |
+
AOTAutograd is functional so that future optimization passes do not reorder
|
| 77 |
+
these operators. This is done through threading "effect tokens" through the
|
| 78 |
+
graph to enforce data dependence between side effectful ops.
|
| 79 |
+
|
| 80 |
+
The tokens are basically dummy values (torch.tensor([])). We create a token
|
| 81 |
+
per "effect type", which are enumerated in the _EffectType enum.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def __init__(self) -> None:
|
| 85 |
+
super().__init__("with_effects")
|
| 86 |
+
|
| 87 |
+
def __call__(
|
| 88 |
+
self,
|
| 89 |
+
token,
|
| 90 |
+
op: OpType,
|
| 91 |
+
*args: tuple[Any, ...],
|
| 92 |
+
**kwargs: dict[str, Any],
|
| 93 |
+
) -> tuple[Any, ...]:
|
| 94 |
+
if not isinstance(op, (torch._ops.HigherOrderOperator, torch._ops.OpOverload)):
|
| 95 |
+
raise AssertionError(
|
| 96 |
+
f"op must be HigherOrderOperator or OpOverload, got {type(op)}"
|
| 97 |
+
)
|
| 98 |
+
if has_aliasing(op):
|
| 99 |
+
raise AssertionError("Ops with aliasing is not supported")
|
| 100 |
+
if not isinstance(kwargs, dict):
|
| 101 |
+
raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}")
|
| 102 |
+
# pyrefly: ignore [missing-attribute]
|
| 103 |
+
return super().__call__(token, op, *args, **kwargs)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
with_effects = WithEffects()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def has_aliasing(op: OpType):
|
| 110 |
+
# NOT FOR PUBLIC USE
|
| 111 |
+
if isinstance(op, torch._ops.HigherOrderOperator):
|
| 112 |
+
return False
|
| 113 |
+
|
| 114 |
+
for arg in op._schema.arguments:
|
| 115 |
+
if arg.alias_info is not None:
|
| 116 |
+
return True
|
| 117 |
+
for arg in op._schema.returns:
|
| 118 |
+
if arg.alias_info is not None:
|
| 119 |
+
return True
|
| 120 |
+
return False
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def has_effects(op) -> bool:
|
| 124 |
+
return (
|
| 125 |
+
isinstance(op, (torch._ops.HigherOrderOperator, torch._ops.OpOverload))
|
| 126 |
+
and not has_aliasing(op)
|
| 127 |
+
and _get_effect(op) is not None
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def new_token_tensor() -> torch.Tensor:
|
| 132 |
+
return torch.tensor([])
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@with_effects.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 136 |
+
def with_effects_dense(
|
| 137 |
+
token: torch.Tensor,
|
| 138 |
+
op: torch._ops.OpOverload,
|
| 139 |
+
*args: tuple[Any, ...],
|
| 140 |
+
**kwargs: dict[str, Any],
|
| 141 |
+
) -> tuple[torch.Tensor, ...]:
|
| 142 |
+
out = op(*args, **kwargs)
|
| 143 |
+
new_token = new_token_tensor()
|
| 144 |
+
# [NOTE: with_effects return type]
|
| 145 |
+
# Note that we should only do *out for tuple type, but not list type.
|
| 146 |
+
# This is to match the schema of the op.
|
| 147 |
+
# For tuple output, the length of schema output is the same as the length of out.
|
| 148 |
+
# For list output, the length of schema output is 1 (e.g. Tensor[]) regardless of the
|
| 149 |
+
# length of the list.
|
| 150 |
+
if isinstance(out, tuple):
|
| 151 |
+
return (new_token, *out)
|
| 152 |
+
return (new_token, out)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@with_effects.py_impl(FakeTensorMode)
|
| 156 |
+
def with_effects_fake(
|
| 157 |
+
mode,
|
| 158 |
+
token: torch.Tensor,
|
| 159 |
+
op: torch._ops.OpOverload,
|
| 160 |
+
*args: tuple[Any, ...],
|
| 161 |
+
**kwargs: dict[str, Any],
|
| 162 |
+
) -> tuple[torch.Tensor, ...]:
|
| 163 |
+
with mode:
|
| 164 |
+
result = with_effects_dense(token, op, *args, **kwargs)
|
| 165 |
+
return result
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@with_effects.py_impl(ProxyTorchDispatchMode)
|
| 169 |
+
def with_effects_proxy(
|
| 170 |
+
mode,
|
| 171 |
+
token: torch.Tensor,
|
| 172 |
+
op: torch._ops.OpOverload,
|
| 173 |
+
*args: tuple[Any, ...],
|
| 174 |
+
**kwargs: dict[str, Any],
|
| 175 |
+
) -> tuple[torch.Tensor, ...]:
|
| 176 |
+
with disable_proxy_modes_tracing():
|
| 177 |
+
out = with_effects(token, op, *args, **kwargs)
|
| 178 |
+
|
| 179 |
+
proxy_token = mode.tracer.unwrap_proxy(token)
|
| 180 |
+
proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args)
|
| 181 |
+
proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs)
|
| 182 |
+
|
| 183 |
+
from torch.fx.node import has_side_effect
|
| 184 |
+
|
| 185 |
+
# To avoid the being DCEed by graph.eliminate_dead_code if they.
|
| 186 |
+
# don't have output or their outputs are not used.
|
| 187 |
+
has_side_effect(op)
|
| 188 |
+
|
| 189 |
+
out_proxy = mode.tracer.create_proxy(
|
| 190 |
+
"call_function",
|
| 191 |
+
with_effects,
|
| 192 |
+
(proxy_token, op, *proxy_args),
|
| 193 |
+
proxy_kwargs,
|
| 194 |
+
)
|
| 195 |
+
result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
|
| 196 |
+
return result
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
with_effects.fallthrough(DispatchKey.AutogradCPU)
|
| 200 |
+
with_effects.fallthrough(DispatchKey.AutogradCUDA)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
@with_effects.py_functionalize_impl
|
| 204 |
+
def with_effects_functional(
|
| 205 |
+
ctx,
|
| 206 |
+
token: torch.Tensor,
|
| 207 |
+
op: torch._ops.OpOverload,
|
| 208 |
+
*args: tuple[Any, ...],
|
| 209 |
+
**kwargs: dict[str, Any],
|
| 210 |
+
) -> tuple[torch.Tensor, ...]:
|
| 211 |
+
# with_effects is already functional, so just re-emit it.
|
| 212 |
+
unwrapped_token, unwrapped_args, unwrapped_kwargs = ctx.unwrap_tensors(
|
| 213 |
+
[token, args, kwargs]
|
| 214 |
+
)
|
| 215 |
+
with ctx.redispatch_to_next():
|
| 216 |
+
result = with_effects(unwrapped_token, op, *unwrapped_args, **unwrapped_kwargs)
|
| 217 |
+
return ctx.wrap_tensors(result)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
_EFFECTFUL_HOPS_WITH_SCHEMA = {hop_print, invoke_leaf_function}
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _get_schema(op, args, kwargs: dict | None = None) -> torch.FunctionSchema:
|
| 224 |
+
if isinstance(op, torch._ops.OpOverload):
|
| 225 |
+
return op._schema
|
| 226 |
+
elif op == call_torchbind:
|
| 227 |
+
return getattr(args[0], args[1]).schema
|
| 228 |
+
elif op in _EFFECTFUL_HOPS_WITH_SCHEMA:
|
| 229 |
+
extra_kwargs = kwargs or {}
|
| 230 |
+
return op.gen_schema(*args, **extra_kwargs)
|
| 231 |
+
else:
|
| 232 |
+
raise RuntimeError(f"Unable to get schema for op {op}")
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def handle_effects(
|
| 236 |
+
allow_token_discovery: bool,
|
| 237 |
+
tokens: dict[_EffectType, torch.Tensor],
|
| 238 |
+
op: OpType,
|
| 239 |
+
args: tuple[Any, ...],
|
| 240 |
+
kwargs: dict[str, Any],
|
| 241 |
+
) -> Any:
|
| 242 |
+
"""
|
| 243 |
+
Args:
|
| 244 |
+
allow_token_discovery: Whether or not we are discovering tokens. If this
|
| 245 |
+
is true, we will create a token for every side effect type seen that
|
| 246 |
+
does not have a token assigned yet. If this is false, the tokens
|
| 247 |
+
should've all been created ahead of time, so we will error if there is
|
| 248 |
+
no token mapping to every effect type.
|
| 249 |
+
|
| 250 |
+
tokens: Map of effect type to tokens. This is to chain operators of the
|
| 251 |
+
same effects together so that they do not get reordered in later
|
| 252 |
+
optimization passes.
|
| 253 |
+
"""
|
| 254 |
+
|
| 255 |
+
# Get a token. We can't do `tokens.get(op, torch.tensor([]))` because
|
| 256 |
+
# this will create an empty tensor during proxy mode tracing if the token
|
| 257 |
+
# doesn't exist. But the tokens should always exist during proxy mode tracing.
|
| 258 |
+
key = _get_effect(op)
|
| 259 |
+
if key is None:
|
| 260 |
+
raise AssertionError(f"effect key must not be None for op {op}")
|
| 261 |
+
if key not in tokens:
|
| 262 |
+
if not allow_token_discovery:
|
| 263 |
+
raise AssertionError(
|
| 264 |
+
f"Could not find a token for effect {key} which came from the function {op}"
|
| 265 |
+
)
|
| 266 |
+
proxy_tensor_mode = torch._C._get_dispatch_mode(
|
| 267 |
+
torch._C._TorchDispatchModeKey.PROXY
|
| 268 |
+
)
|
| 269 |
+
if proxy_tensor_mode is not None:
|
| 270 |
+
# If we discovered a new token during tracing, we are in backward.
|
| 271 |
+
# Then we patch the graph, adding additional tangents_token as input to the joint graph.
|
| 272 |
+
tracer = proxy_tensor_mode.tracer
|
| 273 |
+
|
| 274 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 275 |
+
disable_proxy_modes_tracing,
|
| 276 |
+
track_tensor_tree,
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
with disable_proxy_modes_tracing():
|
| 280 |
+
token_tensor = new_token_tensor()
|
| 281 |
+
|
| 282 |
+
token_proxy = proxy_tensor_mode.tracer.create_proxy(
|
| 283 |
+
"placeholder", "tangents_token", (), {}, name="tangents_token"
|
| 284 |
+
)
|
| 285 |
+
track_tensor_tree(token_tensor, token_proxy, constant=None, tracer=tracer)
|
| 286 |
+
|
| 287 |
+
tokens[key] = token_tensor
|
| 288 |
+
else:
|
| 289 |
+
tokens[key] = new_token_tensor()
|
| 290 |
+
|
| 291 |
+
token = tokens[key]
|
| 292 |
+
|
| 293 |
+
from torch._subclasses.functional_tensor import PythonFunctionalizeAPI
|
| 294 |
+
|
| 295 |
+
ctx = PythonFunctionalizeAPI()
|
| 296 |
+
|
| 297 |
+
unwrapped_token = ctx.unwrap_tensors([token])[0]
|
| 298 |
+
unwrapped_args = ctx.unwrap_tensors(args)
|
| 299 |
+
unwrapped_kwargs = ctx.unwrap_tensors(kwargs) # type: ignore[arg-type]
|
| 300 |
+
with ctx.redispatch_to_next():
|
| 301 |
+
(new_token, *unwrapped_outs) = with_effects(
|
| 302 |
+
unwrapped_token, op, *unwrapped_args, **unwrapped_kwargs
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
schema = _get_schema(op, unwrapped_args, unwrapped_kwargs)
|
| 306 |
+
|
| 307 |
+
if isinstance(schema, HopSchema):
|
| 308 |
+
if len(schema.returns) == 0:
|
| 309 |
+
unwrapped_outs = ()
|
| 310 |
+
else:
|
| 311 |
+
if len(unwrapped_outs) != len(schema.returns):
|
| 312 |
+
raise AssertionError(
|
| 313 |
+
f"expected {len(schema.returns)} outputs but got {len(unwrapped_outs)}"
|
| 314 |
+
)
|
| 315 |
+
unwrapped_outs = tuple(unwrapped_outs)
|
| 316 |
+
elif len(schema.returns) == 0:
|
| 317 |
+
if unwrapped_outs[0] is not None:
|
| 318 |
+
raise AssertionError(f"expected no outputs but got {unwrapped_outs[0]}")
|
| 319 |
+
unwrapped_outs = None # type: ignore[assignment]
|
| 320 |
+
elif len(schema.returns) == 1:
|
| 321 |
+
if len(unwrapped_outs) != 1:
|
| 322 |
+
raise AssertionError(f"expected 1 output but got {len(unwrapped_outs)}")
|
| 323 |
+
unwrapped_outs = unwrapped_outs[0]
|
| 324 |
+
else:
|
| 325 |
+
if len(unwrapped_outs) != len(schema.returns):
|
| 326 |
+
raise AssertionError(
|
| 327 |
+
f"expected {len(schema.returns)} outputs but got {len(unwrapped_outs)}"
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
# Add the newly created token into the tokens map for a following call to
|
| 331 |
+
# use this token.
|
| 332 |
+
wrapped_token = ctx.wrap_tensors(new_token)
|
| 333 |
+
if not isinstance(wrapped_token, torch.Tensor):
|
| 334 |
+
raise AssertionError(
|
| 335 |
+
f"expected wrapped_token to be torch.Tensor, got {type(wrapped_token)}"
|
| 336 |
+
)
|
| 337 |
+
tokens[key] = wrapped_token
|
| 338 |
+
|
| 339 |
+
# pyrefly: ignore [bad-argument-type]
|
| 340 |
+
return ctx.wrap_tensors(unwrapped_outs)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/executorch_call_delegate.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# This source code is licensed under the BSD-style license found in the
|
| 7 |
+
# LICENSE file in the root directory of this source tree.
|
| 8 |
+
|
| 9 |
+
# pyre-strict
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from typing import Any, cast
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.utils._pytree as pytree
|
| 17 |
+
from torch._ops import HigherOrderOperator
|
| 18 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 19 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 20 |
+
disable_proxy_modes_tracing,
|
| 21 |
+
get_proxy_slot,
|
| 22 |
+
ProxyTorchDispatchMode,
|
| 23 |
+
track_tensor_tree,
|
| 24 |
+
)
|
| 25 |
+
from torch.utils._pytree import tree_flatten
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ExecutorchCallDelegate(HigherOrderOperator):
|
| 29 |
+
def __init__(self):
|
| 30 |
+
super().__init__("executorch_call_delegate")
|
| 31 |
+
|
| 32 |
+
def __call__(self, lowered_module, *args):
|
| 33 |
+
# pyrefly: ignore [missing-attribute]
|
| 34 |
+
return super().__call__(lowered_module, *args)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
executorch_call_delegate = ExecutorchCallDelegate()
|
| 38 |
+
executorch_call_delegate.fallthrough(torch._C.DispatchKey.PythonDispatcher)
|
| 39 |
+
executorch_call_delegate.fallthrough(torch._C.DispatchKey.PythonTLSSnapshot)
|
| 40 |
+
executorch_call_delegate.fallthrough(torch._C.DispatchKey.ADInplaceOrView)
|
| 41 |
+
executorch_call_delegate.fallthrough(torch._C.DispatchKey.AutocastCPU)
|
| 42 |
+
|
| 43 |
+
LOWERED_BACKEND_MODULE_TYPE = "LoweredBackendModule"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# pyre-ignore
|
| 47 |
+
def trace_call_delegate(proxy_mode, func_overload, lowered_module, *args):
|
| 48 |
+
# pyre-ignore
|
| 49 |
+
def _unwrap_proxy(e):
|
| 50 |
+
if not isinstance(e, (torch.Tensor, torch.SymInt, torch.SymFloat)):
|
| 51 |
+
return e
|
| 52 |
+
return get_proxy_slot(
|
| 53 |
+
cast(torch.Tensor, e),
|
| 54 |
+
proxy_mode.tracer,
|
| 55 |
+
e,
|
| 56 |
+
lambda e: e.proxy, # type: ignore[attr-defined]
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
if not is_lowered_module(lowered_module):
|
| 60 |
+
raise ValueError(
|
| 61 |
+
"executorch_call_delegate()'s first argument must be a LoweredBackendModule"
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
with disable_proxy_modes_tracing():
|
| 65 |
+
out = call_delegate_cpu(lowered_module, *args)
|
| 66 |
+
|
| 67 |
+
get_lowered_module_name(proxy_mode.tracer.root, lowered_module)
|
| 68 |
+
|
| 69 |
+
node_args = (lowered_module, *args)
|
| 70 |
+
proxy_args = pytree.tree_map(_unwrap_proxy, node_args)
|
| 71 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 72 |
+
"call_function", func_overload, proxy_args, {}, name="executorch_call_delegate"
|
| 73 |
+
)
|
| 74 |
+
return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@executorch_call_delegate.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd)
|
| 78 |
+
# pyre-ignore
|
| 79 |
+
def call_delegate_cpu(lowered_module, *args):
|
| 80 |
+
# FX creates this immutable_dict/list concept. Get rid of this.
|
| 81 |
+
map_types: dict[type, type] = {
|
| 82 |
+
torch.fx.immutable_collections.immutable_dict: dict,
|
| 83 |
+
torch.fx.immutable_collections.immutable_list: list,
|
| 84 |
+
}
|
| 85 |
+
new_args = pytree.tree_map_only(
|
| 86 |
+
tuple(map_types.keys()),
|
| 87 |
+
lambda a: map_types[type(a)](a),
|
| 88 |
+
args,
|
| 89 |
+
lambda a: isinstance(a, tuple(map_types.keys())),
|
| 90 |
+
)
|
| 91 |
+
return lowered_module.original_module.module()(*new_args)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@executorch_call_delegate.py_autograd_impl
|
| 95 |
+
# pyre-ignore
|
| 96 |
+
def call_delegate_autograd(lowered_module, *args):
|
| 97 |
+
# TODO: support autograd
|
| 98 |
+
flat_operands, _ = tree_flatten([lowered_module, *args])
|
| 99 |
+
requires_grad = any(
|
| 100 |
+
f.requires_grad for f in flat_operands if isinstance(f, torch.Tensor)
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
with torch._C._ExcludeDispatchKeyGuard(
|
| 104 |
+
torch._C.DispatchKeySet(torch._C.DispatchKey.AutogradCPU)
|
| 105 |
+
):
|
| 106 |
+
res = executorch_call_delegate(lowered_module, *args)
|
| 107 |
+
|
| 108 |
+
if requires_grad:
|
| 109 |
+
# Create aliases of the output that has requires_grad=True. We need
|
| 110 |
+
# at least one of the inputs to err_fn to require grad so that the
|
| 111 |
+
# output will have a grad_fn.
|
| 112 |
+
|
| 113 |
+
# pyre-ignore
|
| 114 |
+
def fake_requires_grad(var):
|
| 115 |
+
if var is not None:
|
| 116 |
+
var = var.detach()
|
| 117 |
+
if torch.is_floating_point(var) or torch.is_complex(var):
|
| 118 |
+
var.requires_grad = True
|
| 119 |
+
return var
|
| 120 |
+
|
| 121 |
+
return pytree.tree_map_only(torch.Tensor, fake_requires_grad, res)
|
| 122 |
+
|
| 123 |
+
return res
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@executorch_call_delegate.py_impl(ProxyTorchDispatchMode)
|
| 127 |
+
# pyre-ignore
|
| 128 |
+
def call_delegate_proxy_torch_dispatch_mode(mode, lowered_module, *args):
|
| 129 |
+
res = trace_call_delegate(mode, executorch_call_delegate, lowered_module, *args)
|
| 130 |
+
return res
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@executorch_call_delegate.py_impl(FakeTensorMode)
|
| 134 |
+
# pyre-ignore
|
| 135 |
+
def call_delegate_fake_tensor_mode(mode, lowered_module, *args):
|
| 136 |
+
with mode:
|
| 137 |
+
return call_delegate_cpu(lowered_module, *args)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@executorch_call_delegate.py_functionalize_impl
|
| 141 |
+
# pyre-ignore
|
| 142 |
+
def call_delegate_functionalize(ctx, lowered_module, *args):
|
| 143 |
+
unwrapped_args = tuple(ctx.unwrap_tensors(arg) for arg in args)
|
| 144 |
+
with ctx.redispatch_to_next():
|
| 145 |
+
res = executorch_call_delegate(lowered_module, *unwrapped_args)
|
| 146 |
+
return ctx.wrap_tensors(res)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# pyre-ignore: Missing parameter annotation [2]: Parameter `obj` must have a type other than `Any`.Pyre
|
| 150 |
+
def is_lowered_module(obj: Any) -> bool:
|
| 151 |
+
"""
|
| 152 |
+
This function is added to avoid using isinstance(obj,
|
| 153 |
+
LoweredBackendModule) as it will import LoweredBackendModule, which may
|
| 154 |
+
cause a circular import.
|
| 155 |
+
"""
|
| 156 |
+
return type(obj).__name__ == LOWERED_BACKEND_MODULE_TYPE
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def get_lowered_module_name(
|
| 160 |
+
root: torch.nn.Module,
|
| 161 |
+
# pyre-ignore: Undefined or invalid type [11]: Annotation `LoweredBackendModule` is not defined as a type.
|
| 162 |
+
lowered_module: LOWERED_BACKEND_MODULE_TYPE, # type: ignore[valid-type]
|
| 163 |
+
) -> str:
|
| 164 |
+
"""
|
| 165 |
+
Adds the given lowered_module into the given root module and returns the
|
| 166 |
+
name of the module added.
|
| 167 |
+
"""
|
| 168 |
+
# Find a qualifying name for the lowered submodule
|
| 169 |
+
qualname = None
|
| 170 |
+
i = 0
|
| 171 |
+
while True:
|
| 172 |
+
qualname = f"lowered_module_{i}"
|
| 173 |
+
if not hasattr(root, qualname):
|
| 174 |
+
break
|
| 175 |
+
i += 1
|
| 176 |
+
if qualname is None:
|
| 177 |
+
raise AssertionError(
|
| 178 |
+
"qualname must not be None after finding unused module slot"
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
root.add_module(qualname, lowered_module)
|
| 182 |
+
return qualname
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/flat_apply.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import typing
|
| 2 |
+
from collections.abc import Callable, Sequence
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Generic, overload, TypeAlias, TypeVar
|
| 5 |
+
from typing_extensions import ParamSpec, TypeIs, TypeVarTuple, Unpack
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.fx.node
|
| 9 |
+
import torch.utils._pytree as pytree
|
| 10 |
+
from torch._library.fake_class_registry import FakeScriptObject
|
| 11 |
+
from torch._library.opaque_object import is_opaque_type
|
| 12 |
+
from torch._ops import HigherOrderOperator
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
_R = TypeVar("_R")
|
| 16 |
+
_P = ParamSpec("_P")
|
| 17 |
+
_Ts = TypeVarTuple("_Ts")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def is_graphable(val: object) -> TypeIs[torch.fx.node.BaseArgumentTypes]:
|
| 21 |
+
"""Definition: a graphable type is a type that is an acceptable input/output type to a FX node."""
|
| 22 |
+
return isinstance(
|
| 23 |
+
val, (*torch.fx.node.base_types, FakeScriptObject)
|
| 24 |
+
) or is_opaque_type(type(val))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def is_graphable_type(typ: type[object]) -> bool:
|
| 28 |
+
"""Return whether the given type is graphable."""
|
| 29 |
+
return (
|
| 30 |
+
issubclass(typ, torch.fx.node.base_types)
|
| 31 |
+
or is_opaque_type(typ)
|
| 32 |
+
or issubclass(typ, FakeScriptObject)
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def to_graphable(stuff: pytree.PyTree) -> tuple[list[object], pytree.TreeSpec]:
|
| 37 |
+
"""Flattens stuff into a flat list of graphable types."""
|
| 38 |
+
# We can consider preserving things like List[int] to improve
|
| 39 |
+
# perf and readability (right now that is all flattened out)
|
| 40 |
+
flat_args, spec = pytree.tree_flatten(stuff)
|
| 41 |
+
for arg in flat_args:
|
| 42 |
+
if not is_graphable(arg):
|
| 43 |
+
raise RuntimeError(
|
| 44 |
+
f"Expected all pytree.tree_leaves of (args, kwargs) to be graphable types, but found "
|
| 45 |
+
f"non-fx-graphable type {type(arg)}. If this type is meant to be constant, mark it as "
|
| 46 |
+
f"via pytree.register_constant; otherwise, register it as a pytree."
|
| 47 |
+
)
|
| 48 |
+
return flat_args, spec
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def from_graphable(
|
| 52 |
+
flat_args: tuple[Unpack[_Ts]], spec: pytree.TreeSpec
|
| 53 |
+
) -> pytree.PyTree:
|
| 54 |
+
"""The inverse of to_graphable."""
|
| 55 |
+
stuff = pytree.tree_unflatten(flat_args, spec)
|
| 56 |
+
return stuff
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def func_to_graphable(
|
| 60 |
+
func: Callable[..., object],
|
| 61 |
+
) -> tuple[list[object], pytree.TreeSpec]:
|
| 62 |
+
"""
|
| 63 |
+
Pack and flatten a function type into graphable types.
|
| 64 |
+
This is useful for legalizing the function argument of `flat_apply`.
|
| 65 |
+
"""
|
| 66 |
+
return pytree.tree_flatten(_ConstantFunction(func))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@dataclass(frozen=True, slots=True)
|
| 70 |
+
class _ConstantFunction(Generic[_P, _R]):
|
| 71 |
+
func: Callable[_P, _R]
|
| 72 |
+
|
| 73 |
+
def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
|
| 74 |
+
return self.func(*args, **kwargs)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
pytree.register_constant(_ConstantFunction)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
_OpTypes = (
|
| 81 |
+
torch._ops.OpOverload | torch._ops.OpOverloadPacket | torch._ops.HigherOrderOperator
|
| 82 |
+
)
|
| 83 |
+
_op_types = typing.get_args(_OpTypes)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
_Base: TypeAlias = torch.fx.node.BaseArgumentTypes
|
| 87 |
+
# pyrefly bug: pyrefly is complaining: Expected a type form, got instance of `Literal['_FXOutput']
|
| 88 |
+
# pyrefly: ignore[not-a-type]
|
| 89 |
+
_FXOutput = _Base | Sequence["_FXOutput"]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class FlatApply(HigherOrderOperator):
|
| 93 |
+
def __init__(self) -> None:
|
| 94 |
+
super().__init__("flat_apply")
|
| 95 |
+
|
| 96 |
+
def __call__(
|
| 97 |
+
self,
|
| 98 |
+
func: _OpTypes | pytree.TreeSpec,
|
| 99 |
+
in_spec: pytree.TreeSpec,
|
| 100 |
+
*flat_args: Unpack[_Ts],
|
| 101 |
+
# If True then the output is checked to be valid. If False then it is up
|
| 102 |
+
# to the caller to ensure the output is appropriate.
|
| 103 |
+
checked_output: bool = True,
|
| 104 |
+
**_unused: object,
|
| 105 |
+
) -> object:
|
| 106 |
+
"""
|
| 107 |
+
Functions that take in non-graphable types cannot directly be put into FX graph.
|
| 108 |
+
|
| 109 |
+
Given func(*args, **kwargs), if all of the non-graphable types are pytrees,
|
| 110 |
+
then we're able to store a call to flat_apply(func, in_spec, *flat_args) in the FX graph.
|
| 111 |
+
|
| 112 |
+
The semantics of flat_apply(func, in_spec, *flat_args) are roughly equivalent to:
|
| 113 |
+
|
| 114 |
+
>>> def flat_apply_impl(func, in_spec, *flat_args):
|
| 115 |
+
>>> args, kwargs = pytree.tree_unflatten(flat_args, in_spec)
|
| 116 |
+
>>> output = func(*args, **kwargs)
|
| 117 |
+
>>> return output
|
| 118 |
+
|
| 119 |
+
flat_apply supports the following two cases:
|
| 120 |
+
- an input type is a container type (e.g. of tensors) registered as a pytree.
|
| 121 |
+
We'll tree_flatten the input type and store the spec.
|
| 122 |
+
- an input type is a constant type (i.e. torch.compile will specialize on it)
|
| 123 |
+
registered with pytree.register_constant. The constant type goes directly
|
| 124 |
+
into the spec.
|
| 125 |
+
"""
|
| 126 |
+
if not (
|
| 127 |
+
isinstance(func, _op_types)
|
| 128 |
+
or is_opaque_type(type(func))
|
| 129 |
+
or pytree._is_constant_holder(func)
|
| 130 |
+
):
|
| 131 |
+
raise AssertionError(
|
| 132 |
+
f"func must be an op type, constant holder, or opaque callable, got {type(func)}"
|
| 133 |
+
)
|
| 134 |
+
if len(_unused) != 0:
|
| 135 |
+
raise AssertionError(f"unexpected keyword arguments: {_unused}")
|
| 136 |
+
# pyrefly: ignore[bad-argument-type] # pyrefly bug?
|
| 137 |
+
return impl(func, in_spec, flat_args, checked_output)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@overload
|
| 141 |
+
def is_valid_output(x: tuple[object, ...]) -> TypeIs[tuple[_FXOutput, ...]]: ...
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@overload
|
| 145 |
+
def is_valid_output(x: Sequence[object]) -> TypeIs[Sequence[_FXOutput]]: ...
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def is_valid_output(x: object) -> bool:
|
| 149 |
+
if isinstance(x, (tuple, list)):
|
| 150 |
+
return all(map(is_valid_output, x))
|
| 151 |
+
return is_graphable(x)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def impl(
|
| 155 |
+
func: _OpTypes | pytree.TreeSpec,
|
| 156 |
+
in_spec: pytree.TreeSpec,
|
| 157 |
+
flat_args: tuple[Unpack[_Ts]],
|
| 158 |
+
checked_output: bool,
|
| 159 |
+
) -> _FXOutput:
|
| 160 |
+
if isinstance(func, pytree.TreeSpec):
|
| 161 |
+
# assume _ConstantFunction
|
| 162 |
+
func = pytree._retrieve_constant(func)
|
| 163 |
+
if not isinstance(func, _ConstantFunction):
|
| 164 |
+
raise AssertionError(
|
| 165 |
+
f"expected retrieved constant to be _ConstantFunction, got {type(func)}"
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
from torch._higher_order_ops.invoke_leaf_function import unflatten_args_with_modules
|
| 169 |
+
|
| 170 |
+
with unflatten_args_with_modules(flat_args, in_spec) as (args, kwargs):
|
| 171 |
+
out = func(*args, **kwargs)
|
| 172 |
+
|
| 173 |
+
if checked_output:
|
| 174 |
+
# For "normal" usage all outputs must either be graphable or
|
| 175 |
+
# lists/tuples of graphables.
|
| 176 |
+
if not is_valid_output(out):
|
| 177 |
+
raise AssertionError(
|
| 178 |
+
f"output must be graphable or nested list/tuple of graphables, got {type(out)}"
|
| 179 |
+
)
|
| 180 |
+
return out
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
flat_apply = FlatApply()
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/flex_attention.py
ADDED
|
@@ -0,0 +1,1464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from collections.abc import Callable, Sequence
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.utils._pytree as pytree
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
from torch._C import DispatchKey
|
| 9 |
+
from torch._higher_order_ops.utils import (
|
| 10 |
+
_has_potential_branch_input_mutation,
|
| 11 |
+
_maybe_reenter_make_fx,
|
| 12 |
+
autograd_not_implemented,
|
| 13 |
+
has_user_subclass,
|
| 14 |
+
redirect_to_mode,
|
| 15 |
+
reenter_make_fx,
|
| 16 |
+
register_fake,
|
| 17 |
+
save_values_for_backward,
|
| 18 |
+
saved_values,
|
| 19 |
+
UnsupportedAliasMutationException,
|
| 20 |
+
validate_subgraph_args_types,
|
| 21 |
+
)
|
| 22 |
+
from torch._ops import HigherOrderOperator
|
| 23 |
+
from torch._subclasses import FakeTensor
|
| 24 |
+
from torch.amp.autocast_mode import _cast as _autocast_cast
|
| 25 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 26 |
+
make_fx,
|
| 27 |
+
ProxyTorchDispatchMode,
|
| 28 |
+
track_tensor_tree,
|
| 29 |
+
)
|
| 30 |
+
from torch.fx.graph_module import GraphModule
|
| 31 |
+
from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# Duplicate of _inductor/kernel/flex_attention.py to avoid circular import
|
| 35 |
+
def _construct_strides(
|
| 36 |
+
sizes: Sequence[int],
|
| 37 |
+
fill_order: Sequence[int],
|
| 38 |
+
) -> Sequence[int]:
|
| 39 |
+
"""From a list of sizes and a fill order, construct the strides of the permuted tensor."""
|
| 40 |
+
# Initialize strides
|
| 41 |
+
if len(sizes) != len(fill_order):
|
| 42 |
+
raise AssertionError(
|
| 43 |
+
f"Length of sizes must match the length of the fill order, got {len(sizes)} vs {len(fill_order)}"
|
| 44 |
+
)
|
| 45 |
+
strides = [0] * len(sizes)
|
| 46 |
+
|
| 47 |
+
# Start with stride 1 for the innermost dimension
|
| 48 |
+
current_stride = 1
|
| 49 |
+
|
| 50 |
+
# Iterate through the fill order populating strides
|
| 51 |
+
for dim in fill_order:
|
| 52 |
+
strides[dim] = current_stride
|
| 53 |
+
current_stride *= sizes[dim]
|
| 54 |
+
|
| 55 |
+
return strides
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _permute_strides(out: torch.Tensor, query_strides: tuple[int, ...]) -> torch.Tensor:
|
| 59 |
+
"""
|
| 60 |
+
Create a new tensor with the same data and shape as the input,
|
| 61 |
+
but with strides permuted based on the input tensor's stride order.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
out (torch.Tensor): The output tensor of attention.
|
| 65 |
+
query_strides (List[int]): The stride order of the input query tensor
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
torch.Tensor: A new tensor with same shape and data as the input,
|
| 69 |
+
but with strides permuted based on the query tensor's stride order.
|
| 70 |
+
"""
|
| 71 |
+
from torch._inductor.ir import get_fill_order
|
| 72 |
+
|
| 73 |
+
fill_order = get_fill_order(query_strides)
|
| 74 |
+
if out.storage_offset() != 0:
|
| 75 |
+
raise AssertionError(
|
| 76 |
+
f"Only support storage_offset == 0, got {out.storage_offset()}"
|
| 77 |
+
)
|
| 78 |
+
out_strides = _construct_strides(out.shape, fill_order)
|
| 79 |
+
|
| 80 |
+
# Attention kernels require stride[-1]=1 for efficient memory access.
|
| 81 |
+
# Ensure this by moving last dim to front of fill_order if needed.
|
| 82 |
+
if out_strides[-1] != 1:
|
| 83 |
+
last_dim = len(out.shape) - 1
|
| 84 |
+
fill_order = list(fill_order)
|
| 85 |
+
fill_order.remove(last_dim)
|
| 86 |
+
fill_order = [last_dim] + fill_order
|
| 87 |
+
out_strides = _construct_strides(out.shape, fill_order)
|
| 88 |
+
|
| 89 |
+
new_out = out.new_empty_strided(out.shape, out_strides)
|
| 90 |
+
new_out.copy_(out)
|
| 91 |
+
return new_out
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class FlexAttentionHOP(HigherOrderOperator):
|
| 95 |
+
def __init__(self) -> None:
|
| 96 |
+
super().__init__("flex_attention", cacheable=True)
|
| 97 |
+
|
| 98 |
+
def __call__(
|
| 99 |
+
self,
|
| 100 |
+
query: torch.Tensor,
|
| 101 |
+
key: torch.Tensor,
|
| 102 |
+
value: torch.Tensor,
|
| 103 |
+
score_mod: Callable,
|
| 104 |
+
block_mask: tuple,
|
| 105 |
+
scale: float,
|
| 106 |
+
kernel_options: dict[str, Any],
|
| 107 |
+
score_mod_other_buffers: tuple = (),
|
| 108 |
+
mask_mod_other_buffers: tuple = (),
|
| 109 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 110 |
+
validate_subgraph_args_types(score_mod_other_buffers + mask_mod_other_buffers)
|
| 111 |
+
# pyrefly: ignore [missing-attribute]
|
| 112 |
+
return super().__call__(
|
| 113 |
+
query,
|
| 114 |
+
key,
|
| 115 |
+
value,
|
| 116 |
+
score_mod,
|
| 117 |
+
block_mask,
|
| 118 |
+
scale,
|
| 119 |
+
kernel_options,
|
| 120 |
+
score_mod_other_buffers,
|
| 121 |
+
mask_mod_other_buffers,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
flex_attention = FlexAttentionHOP()
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class FlexAttentionBackwardHOP(HigherOrderOperator):
|
| 129 |
+
def __init__(self) -> None:
|
| 130 |
+
super().__init__("flex_attention_backward", cacheable=True)
|
| 131 |
+
|
| 132 |
+
def __call__(
|
| 133 |
+
self,
|
| 134 |
+
query: torch.Tensor,
|
| 135 |
+
key: torch.Tensor,
|
| 136 |
+
value: torch.Tensor,
|
| 137 |
+
out: torch.Tensor,
|
| 138 |
+
logsumexp: torch.Tensor,
|
| 139 |
+
grad_out: torch.Tensor | None,
|
| 140 |
+
grad_logsumexp: torch.Tensor | None,
|
| 141 |
+
fw_graph: Callable | GraphModule,
|
| 142 |
+
joint_graph: GraphModule,
|
| 143 |
+
block_mask: tuple,
|
| 144 |
+
scale: float,
|
| 145 |
+
kernel_options: dict[str, Any],
|
| 146 |
+
score_mod_other_buffers: tuple = (),
|
| 147 |
+
mask_mod_other_buffers: tuple = (),
|
| 148 |
+
) -> tuple[
|
| 149 |
+
torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]
|
| 150 |
+
]:
|
| 151 |
+
validate_subgraph_args_types(score_mod_other_buffers + mask_mod_other_buffers)
|
| 152 |
+
|
| 153 |
+
# pyrefly: ignore [missing-attribute]
|
| 154 |
+
return super().__call__(
|
| 155 |
+
query,
|
| 156 |
+
key,
|
| 157 |
+
value,
|
| 158 |
+
out,
|
| 159 |
+
logsumexp,
|
| 160 |
+
grad_out,
|
| 161 |
+
grad_logsumexp,
|
| 162 |
+
fw_graph,
|
| 163 |
+
joint_graph,
|
| 164 |
+
block_mask,
|
| 165 |
+
scale,
|
| 166 |
+
kernel_options,
|
| 167 |
+
score_mod_other_buffers,
|
| 168 |
+
mask_mod_other_buffers,
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
flex_attention_backward = FlexAttentionBackwardHOP()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _math_attention_inner(
|
| 176 |
+
query: torch.Tensor,
|
| 177 |
+
key: torch.Tensor,
|
| 178 |
+
value: torch.Tensor,
|
| 179 |
+
score_mod: Callable,
|
| 180 |
+
block_mask: tuple,
|
| 181 |
+
scale: float,
|
| 182 |
+
kernel_options: dict[str, Any],
|
| 183 |
+
score_mod_other_buffers: tuple = (),
|
| 184 |
+
mask_mod_other_buffers: tuple = (),
|
| 185 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 186 |
+
from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
|
| 187 |
+
|
| 188 |
+
working_precision = torch.float64 if query.dtype == torch.float64 else torch.float32
|
| 189 |
+
|
| 190 |
+
scores = query.to(working_precision) @ key.to(working_precision).transpose(-2, -1)
|
| 191 |
+
|
| 192 |
+
b = torch.arange(0, scores.size(0), device=scores.device)
|
| 193 |
+
h = torch.arange(0, scores.size(1), device=scores.device)
|
| 194 |
+
m = torch.arange(0, scores.size(2), device=scores.device)
|
| 195 |
+
n = torch.arange(0, scores.size(3), device=scores.device)
|
| 196 |
+
|
| 197 |
+
captured_buffers_in_dim = (None,) * len(score_mod_other_buffers)
|
| 198 |
+
from torch.nn.attention.flex_attention import _vmap_for_bhqkv
|
| 199 |
+
|
| 200 |
+
# first input is score
|
| 201 |
+
score_mod = _vmap_for_bhqkv(score_mod, prefix=(0,), suffix=captured_buffers_in_dim)
|
| 202 |
+
|
| 203 |
+
mask_mod = block_mask[-1]
|
| 204 |
+
mask_mod_in_dim_buffers = (None,) * len(mask_mod_other_buffers)
|
| 205 |
+
mask_mod = _vmap_for_bhqkv(mask_mod, prefix=(), suffix=mask_mod_in_dim_buffers)
|
| 206 |
+
|
| 207 |
+
with TransformGetItemToIndex():
|
| 208 |
+
scores = (scores * scale).to(working_precision)
|
| 209 |
+
post_mod_scores = torch.where(
|
| 210 |
+
mask_mod(b, h, m, n, *mask_mod_other_buffers),
|
| 211 |
+
score_mod(scores, b, h, m, n, *score_mod_other_buffers),
|
| 212 |
+
torch.tensor(-float("inf"), dtype=working_precision, device=scores.device),
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
return scores, post_mod_scores
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def math_attention(
|
| 219 |
+
query: torch.Tensor,
|
| 220 |
+
key: torch.Tensor,
|
| 221 |
+
value: torch.Tensor,
|
| 222 |
+
score_mod: Callable,
|
| 223 |
+
block_mask: tuple,
|
| 224 |
+
scale: float,
|
| 225 |
+
kernel_options: dict[str, Any],
|
| 226 |
+
score_mod_other_buffers: tuple = (),
|
| 227 |
+
mask_mod_other_buffers: tuple = (),
|
| 228 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 229 |
+
"""Eager implementation
|
| 230 |
+
|
| 231 |
+
This implementation uses vmap to vectorize the score_mod function over the batch, head, m, and n dimensions.
|
| 232 |
+
We then apply the vectorized score_mod function to the scores matrix. Each wrap of vmap applies one of the
|
| 233 |
+
batch, head, m, or n dimensions. We need to apply vmap 4 times to vectorized over all 4 dimensions.
|
| 234 |
+
|
| 235 |
+
Args:
|
| 236 |
+
query: The query tensor
|
| 237 |
+
key: The key tensor
|
| 238 |
+
value: The value tensor
|
| 239 |
+
score_mod: The score_mod function
|
| 240 |
+
other_buffers: Other buffers that are passed to the score_mod function
|
| 241 |
+
|
| 242 |
+
Notes:
|
| 243 |
+
Query and Keys are dtype cast up to float64 (if query.dtype is float64) and float32 otherwise.
|
| 244 |
+
Scores and Values are dtype cast to input query.dtype at the end.
|
| 245 |
+
"""
|
| 246 |
+
# broadcast query & key along head dim for GQA
|
| 247 |
+
G = query.size(1) // key.size(1)
|
| 248 |
+
value = torch.repeat_interleave(value, G, dim=1)
|
| 249 |
+
key = torch.repeat_interleave(key, G, dim=1)
|
| 250 |
+
|
| 251 |
+
Bq, Bkv = query.size(0), key.size(0)
|
| 252 |
+
if not ((Bq == Bkv) or (Bq > 1 and Bkv == 1)):
|
| 253 |
+
raise RuntimeError(f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}")
|
| 254 |
+
|
| 255 |
+
key = key.expand((Bq, *key.size()[1:]))
|
| 256 |
+
value = value.expand((Bq, *value.size()[1:]))
|
| 257 |
+
|
| 258 |
+
_, post_mod_scores = _math_attention_inner(
|
| 259 |
+
query,
|
| 260 |
+
key,
|
| 261 |
+
value,
|
| 262 |
+
score_mod,
|
| 263 |
+
block_mask,
|
| 264 |
+
scale,
|
| 265 |
+
kernel_options,
|
| 266 |
+
score_mod_other_buffers,
|
| 267 |
+
mask_mod_other_buffers,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# Set fully masked rows' sumexp to 0.0
|
| 271 |
+
logsumexp = post_mod_scores.logsumexp(dim=-1)
|
| 272 |
+
masked_rows = torch.all(post_mod_scores == -float("inf"), dim=-1)
|
| 273 |
+
logsumexp = torch.where(masked_rows, -float("inf"), logsumexp)
|
| 274 |
+
|
| 275 |
+
# working precision will be used so no need to cast to fp32
|
| 276 |
+
max_scores = torch.max(post_mod_scores, dim=-1)[0]
|
| 277 |
+
|
| 278 |
+
post_mod_scores = torch._safe_softmax(post_mod_scores, dim=-1)
|
| 279 |
+
|
| 280 |
+
# NB: kernel computes in ln2 space, we always convert back at the top level op, so
|
| 281 |
+
# for math impl we divide by log(2) because we will multiply by log(2)
|
| 282 |
+
|
| 283 |
+
return (
|
| 284 |
+
post_mod_scores.to(query.dtype) @ value.to(query.dtype),
|
| 285 |
+
logsumexp / math.log(2),
|
| 286 |
+
max_scores / math.log(2),
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _flex_attention_autocast_impl(
|
| 291 |
+
query: torch.Tensor,
|
| 292 |
+
key: torch.Tensor,
|
| 293 |
+
value: torch.Tensor,
|
| 294 |
+
score_mod: Callable,
|
| 295 |
+
block_mask: tuple,
|
| 296 |
+
scale: float,
|
| 297 |
+
kernel_options: dict[str, Any],
|
| 298 |
+
score_mod_other_buffers: tuple,
|
| 299 |
+
mask_mod_other_buffers: tuple,
|
| 300 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 301 |
+
"""
|
| 302 |
+
Forward-only autocast shim: cast Q/K/V to the active autocast dtype, then
|
| 303 |
+
redispatch with Autocast keys excluded so we hit the normal implementation.
|
| 304 |
+
"""
|
| 305 |
+
device_type = query.device.type
|
| 306 |
+
autocast_dtype = torch.get_autocast_dtype(device_type)
|
| 307 |
+
|
| 308 |
+
query = _autocast_cast(query, device_type, autocast_dtype)
|
| 309 |
+
key = _autocast_cast(key, device_type, autocast_dtype)
|
| 310 |
+
value = _autocast_cast(value, device_type, autocast_dtype)
|
| 311 |
+
|
| 312 |
+
autocast_keyset = torch._C.DispatchKeySet(
|
| 313 |
+
DispatchKey.AutocastCPU
|
| 314 |
+
) | torch._C.DispatchKeySet(DispatchKey.AutocastCUDA)
|
| 315 |
+
with torch._C._ExcludeDispatchKeyGuard(autocast_keyset):
|
| 316 |
+
return flex_attention(
|
| 317 |
+
query,
|
| 318 |
+
key,
|
| 319 |
+
value,
|
| 320 |
+
score_mod,
|
| 321 |
+
block_mask,
|
| 322 |
+
scale,
|
| 323 |
+
kernel_options,
|
| 324 |
+
score_mod_other_buffers,
|
| 325 |
+
mask_mod_other_buffers,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@flex_attention.py_impl(DispatchKey.AutocastCUDA)
|
| 330 |
+
def flex_attention_autocast_cuda(
|
| 331 |
+
query: torch.Tensor,
|
| 332 |
+
key: torch.Tensor,
|
| 333 |
+
value: torch.Tensor,
|
| 334 |
+
score_mod: Callable,
|
| 335 |
+
block_mask: tuple,
|
| 336 |
+
scale: float,
|
| 337 |
+
kernel_options: dict[str, Any],
|
| 338 |
+
score_mod_other_buffers: tuple = (),
|
| 339 |
+
mask_mod_other_buffers: tuple = (),
|
| 340 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 341 |
+
return _flex_attention_autocast_impl(
|
| 342 |
+
query,
|
| 343 |
+
key,
|
| 344 |
+
value,
|
| 345 |
+
score_mod,
|
| 346 |
+
block_mask,
|
| 347 |
+
scale,
|
| 348 |
+
kernel_options,
|
| 349 |
+
score_mod_other_buffers,
|
| 350 |
+
mask_mod_other_buffers,
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
@flex_attention.py_impl(DispatchKey.AutocastCPU)
|
| 355 |
+
def flex_attention_autocast_cpu(
|
| 356 |
+
query: torch.Tensor,
|
| 357 |
+
key: torch.Tensor,
|
| 358 |
+
value: torch.Tensor,
|
| 359 |
+
score_mod: Callable,
|
| 360 |
+
block_mask: tuple,
|
| 361 |
+
scale: float,
|
| 362 |
+
kernel_options: dict[str, Any],
|
| 363 |
+
score_mod_other_buffers: tuple = (),
|
| 364 |
+
mask_mod_other_buffers: tuple = (),
|
| 365 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 366 |
+
return _flex_attention_autocast_impl(
|
| 367 |
+
query,
|
| 368 |
+
key,
|
| 369 |
+
value,
|
| 370 |
+
score_mod,
|
| 371 |
+
block_mask,
|
| 372 |
+
scale,
|
| 373 |
+
kernel_options,
|
| 374 |
+
score_mod_other_buffers,
|
| 375 |
+
mask_mod_other_buffers,
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
@flex_attention.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 380 |
+
def sdpa_dense(
|
| 381 |
+
query: torch.Tensor,
|
| 382 |
+
key: torch.Tensor,
|
| 383 |
+
value: torch.Tensor,
|
| 384 |
+
score_mod: Callable,
|
| 385 |
+
block_mask: tuple,
|
| 386 |
+
scale: float,
|
| 387 |
+
kernel_options: dict[str, Any],
|
| 388 |
+
score_mod_other_buffers: tuple = (),
|
| 389 |
+
mask_mod_other_buffers: tuple = (),
|
| 390 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 391 |
+
out, lse, max_scores = math_attention(
|
| 392 |
+
query,
|
| 393 |
+
key,
|
| 394 |
+
value,
|
| 395 |
+
score_mod,
|
| 396 |
+
block_mask,
|
| 397 |
+
scale,
|
| 398 |
+
kernel_options,
|
| 399 |
+
score_mod_other_buffers,
|
| 400 |
+
mask_mod_other_buffers,
|
| 401 |
+
)
|
| 402 |
+
out = _permute_strides(out, query.stride())
|
| 403 |
+
return out, lse, max_scores
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def trace_flex_attention(
|
| 407 |
+
proxy_mode: ProxyTorchDispatchMode,
|
| 408 |
+
query: torch.Tensor,
|
| 409 |
+
key: torch.Tensor,
|
| 410 |
+
value: torch.Tensor,
|
| 411 |
+
score_mod: Callable,
|
| 412 |
+
block_mask: tuple,
|
| 413 |
+
scale: float,
|
| 414 |
+
kernel_options: dict[str, Any],
|
| 415 |
+
score_mod_other_buffers: tuple = (),
|
| 416 |
+
mask_mod_other_buffers: tuple = (),
|
| 417 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 418 |
+
"""Traces the flex_attention operator with the given score_mod function and other_buffers.
|
| 419 |
+
|
| 420 |
+
Trace SDPA will call make_fx with "fake" example vals and then trace the score_mod function
|
| 421 |
+
This will produce a GraphModule that will be stored on the root tracer as "sdpa_score". We
|
| 422 |
+
access this graph module in inductor to inline the score_mod function to the triton template.
|
| 423 |
+
"""
|
| 424 |
+
from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
|
| 425 |
+
|
| 426 |
+
example_out = flex_attention(
|
| 427 |
+
query,
|
| 428 |
+
key,
|
| 429 |
+
value,
|
| 430 |
+
score_mod,
|
| 431 |
+
block_mask,
|
| 432 |
+
scale,
|
| 433 |
+
kernel_options,
|
| 434 |
+
score_mod_other_buffers,
|
| 435 |
+
mask_mod_other_buffers,
|
| 436 |
+
)
|
| 437 |
+
example_vals = [query.new_zeros((), requires_grad=query.requires_grad)] + [
|
| 438 |
+
query.new_zeros((), dtype=torch.int) for _ in range(4)
|
| 439 |
+
]
|
| 440 |
+
mask_example_vals = [query.new_zeros((), dtype=torch.int) for _ in range(4)]
|
| 441 |
+
mask_mod = block_mask[-1]
|
| 442 |
+
with TransformGetItemToIndex():
|
| 443 |
+
score_graph = reenter_make_fx(score_mod)(
|
| 444 |
+
*example_vals, *score_mod_other_buffers
|
| 445 |
+
)
|
| 446 |
+
mask_graph = reenter_make_fx(mask_mod)(
|
| 447 |
+
*mask_example_vals, *mask_mod_other_buffers
|
| 448 |
+
)
|
| 449 |
+
if not isinstance(proxy_mode.tracer, torch.fx.Tracer):
|
| 450 |
+
raise AssertionError(
|
| 451 |
+
f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}"
|
| 452 |
+
)
|
| 453 |
+
block_mask = block_mask[:-1] + (mask_graph,)
|
| 454 |
+
qualname = proxy_mode.tracer.get_fresh_qualname("sdpa_score")
|
| 455 |
+
proxy_mode.tracer.root.register_module(qualname, score_graph)
|
| 456 |
+
mask_qualname = proxy_mode.tracer.get_fresh_qualname("sdpa_mask")
|
| 457 |
+
proxy_mode.tracer.root.register_module(mask_qualname, mask_graph)
|
| 458 |
+
node_args = (
|
| 459 |
+
query,
|
| 460 |
+
key,
|
| 461 |
+
value,
|
| 462 |
+
score_graph,
|
| 463 |
+
block_mask,
|
| 464 |
+
scale,
|
| 465 |
+
kernel_options,
|
| 466 |
+
score_mod_other_buffers,
|
| 467 |
+
mask_mod_other_buffers,
|
| 468 |
+
)
|
| 469 |
+
# pyrefly: ignore [missing-attribute]
|
| 470 |
+
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
|
| 471 |
+
with torch.fx.experimental.proxy_tensor.set_original_aten_op(flex_attention):
|
| 472 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 473 |
+
"call_function", flex_attention, proxy_args, {}
|
| 474 |
+
)
|
| 475 |
+
return track_tensor_tree(
|
| 476 |
+
example_out,
|
| 477 |
+
out_proxy,
|
| 478 |
+
constant=None,
|
| 479 |
+
tracer=proxy_mode.tracer,
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
@flex_attention.py_impl(ProxyTorchDispatchMode)
|
| 484 |
+
def flex_attention_proxy_torch_dispatch_mode(
|
| 485 |
+
mode: ProxyTorchDispatchMode,
|
| 486 |
+
query: torch.Tensor,
|
| 487 |
+
key: torch.Tensor,
|
| 488 |
+
value: torch.Tensor,
|
| 489 |
+
score_mod: Callable,
|
| 490 |
+
block_mask: tuple,
|
| 491 |
+
scale: float,
|
| 492 |
+
kernel_options: dict[str, Any],
|
| 493 |
+
score_mod_other_buffers: tuple = (),
|
| 494 |
+
mask_mod_other_buffers: tuple = (),
|
| 495 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 496 |
+
if mode is None:
|
| 497 |
+
raise AssertionError("Mode should always be enabled for python fallback key")
|
| 498 |
+
return trace_flex_attention(
|
| 499 |
+
mode,
|
| 500 |
+
query,
|
| 501 |
+
key,
|
| 502 |
+
value,
|
| 503 |
+
score_mod,
|
| 504 |
+
block_mask,
|
| 505 |
+
scale,
|
| 506 |
+
kernel_options,
|
| 507 |
+
score_mod_other_buffers,
|
| 508 |
+
mask_mod_other_buffers,
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
@flex_attention.py_functionalize_impl
|
| 513 |
+
def flex_attention_functionalize(
|
| 514 |
+
ctx: torch._subclasses.functional_tensor.BaseFunctionalizeAPI,
|
| 515 |
+
query: torch.Tensor,
|
| 516 |
+
key: torch.Tensor,
|
| 517 |
+
value: torch.Tensor,
|
| 518 |
+
score_mod: Callable,
|
| 519 |
+
block_mask: tuple,
|
| 520 |
+
scale: float,
|
| 521 |
+
kernel_options: dict[str, Any],
|
| 522 |
+
score_mod_other_buffers: tuple = (),
|
| 523 |
+
mask_mod_other_buffers: tuple = (),
|
| 524 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 525 |
+
"""Defines the functionalization rules for the flex_attention operator.
|
| 526 |
+
|
| 527 |
+
Write now we are unwrapping each tensor and then redispatching to the next, however we want to
|
| 528 |
+
guard against any mutations in the score_mod function, to the other_buffers since those
|
| 529 |
+
are free variables.
|
| 530 |
+
"""
|
| 531 |
+
from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
|
| 532 |
+
|
| 533 |
+
query_unwrapped = ctx.unwrap_tensors(query)
|
| 534 |
+
key_unwrapped = ctx.unwrap_tensors(key)
|
| 535 |
+
value_unwrapped = ctx.unwrap_tensors(value)
|
| 536 |
+
block_mask_unwrapped = ctx.unwrap_tensors(block_mask)
|
| 537 |
+
score_mod_other_buffers_unwrapped = ctx.unwrap_tensors(score_mod_other_buffers)
|
| 538 |
+
mask_mod_other_buffers_unwrapped = ctx.unwrap_tensors(mask_mod_other_buffers)
|
| 539 |
+
|
| 540 |
+
# Appease the mypy overlords
|
| 541 |
+
if not isinstance(query_unwrapped, torch.Tensor):
|
| 542 |
+
raise AssertionError(
|
| 543 |
+
f"expected query_unwrapped to be torch.Tensor, got {type(query_unwrapped)}"
|
| 544 |
+
)
|
| 545 |
+
if not isinstance(key_unwrapped, torch.Tensor):
|
| 546 |
+
raise AssertionError(
|
| 547 |
+
f"expected key_unwrapped to be torch.Tensor, got {type(key_unwrapped)}"
|
| 548 |
+
)
|
| 549 |
+
if not isinstance(value_unwrapped, torch.Tensor):
|
| 550 |
+
raise AssertionError(
|
| 551 |
+
f"expected value_unwrapped to be torch.Tensor, got {type(value_unwrapped)}"
|
| 552 |
+
)
|
| 553 |
+
if not isinstance(block_mask_unwrapped, tuple):
|
| 554 |
+
raise AssertionError(
|
| 555 |
+
f"expected block_mask_unwrapped to be tuple, got {type(block_mask_unwrapped)}"
|
| 556 |
+
)
|
| 557 |
+
if not isinstance(score_mod_other_buffers_unwrapped, tuple):
|
| 558 |
+
raise AssertionError(
|
| 559 |
+
f"expected score_mod_other_buffers_unwrapped to be tuple, got {type(score_mod_other_buffers_unwrapped)}"
|
| 560 |
+
)
|
| 561 |
+
if not isinstance(mask_mod_other_buffers_unwrapped, tuple):
|
| 562 |
+
raise AssertionError(
|
| 563 |
+
f"expected mask_mod_other_buffers_unwrapped to be tuple, got {type(mask_mod_other_buffers_unwrapped)}"
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
example_vals = (
|
| 567 |
+
[query_unwrapped.new_zeros(())]
|
| 568 |
+
+ [query_unwrapped.new_zeros((), dtype=torch.int) for _ in range(4)]
|
| 569 |
+
+ list(score_mod_other_buffers_unwrapped)
|
| 570 |
+
)
|
| 571 |
+
with ctx.redispatch_to_next():
|
| 572 |
+
functional_score_mod = ctx.functionalize(score_mod)
|
| 573 |
+
pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
|
| 574 |
+
with TransformGetItemToIndex():
|
| 575 |
+
# TODO: So far only the input mutations are checked
|
| 576 |
+
# In the other HOPs, also aliases are checked which is
|
| 577 |
+
# omitted here
|
| 578 |
+
mutates = _has_potential_branch_input_mutation(
|
| 579 |
+
score_mod, example_vals, pre_dispatch
|
| 580 |
+
)
|
| 581 |
+
# The only care about mutations of existing buffers since we can't replay these.
|
| 582 |
+
# However, we can just error if anything is detected
|
| 583 |
+
if mutates:
|
| 584 |
+
raise UnsupportedAliasMutationException("Mutations detected in score_mod")
|
| 585 |
+
|
| 586 |
+
out = flex_attention(
|
| 587 |
+
query_unwrapped,
|
| 588 |
+
key_unwrapped,
|
| 589 |
+
value_unwrapped,
|
| 590 |
+
functional_score_mod,
|
| 591 |
+
block_mask_unwrapped,
|
| 592 |
+
scale,
|
| 593 |
+
kernel_options,
|
| 594 |
+
score_mod_other_buffers_unwrapped,
|
| 595 |
+
mask_mod_other_buffers_unwrapped,
|
| 596 |
+
)
|
| 597 |
+
return ctx.wrap_tensors(out) # type: ignore[return-value, arg-type]
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
@register_fake(flex_attention)
|
| 601 |
+
def flex_attention_fake_impl(
|
| 602 |
+
query: torch.Tensor,
|
| 603 |
+
key: torch.Tensor,
|
| 604 |
+
value: torch.Tensor,
|
| 605 |
+
score_mod: Callable,
|
| 606 |
+
block_mask: tuple,
|
| 607 |
+
scale: float,
|
| 608 |
+
kernel_options: dict[str, Any],
|
| 609 |
+
score_mod_other_buffers: tuple = (),
|
| 610 |
+
mask_mod_other_buffers: tuple = (),
|
| 611 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 612 |
+
if has_user_subclass(
|
| 613 |
+
(
|
| 614 |
+
query,
|
| 615 |
+
key,
|
| 616 |
+
value,
|
| 617 |
+
score_mod,
|
| 618 |
+
block_mask,
|
| 619 |
+
scale,
|
| 620 |
+
kernel_options,
|
| 621 |
+
score_mod_other_buffers,
|
| 622 |
+
mask_mod_other_buffers,
|
| 623 |
+
),
|
| 624 |
+
allowed_subclasses=(FakeTensor,),
|
| 625 |
+
):
|
| 626 |
+
return NotImplemented
|
| 627 |
+
|
| 628 |
+
v_head_dim = value.size(-1)
|
| 629 |
+
batch_size, num_heads, seq_len_q, _q_head_dim = query.shape
|
| 630 |
+
logsumexp = query.new_empty(batch_size, num_heads, seq_len_q, dtype=torch.float32)
|
| 631 |
+
max_scores = query.new_empty(batch_size, num_heads, seq_len_q, dtype=torch.float32)
|
| 632 |
+
out_shape = (batch_size, num_heads, seq_len_q, v_head_dim)
|
| 633 |
+
out = query.new_empty(out_shape)
|
| 634 |
+
out = _permute_strides(out, query.stride())
|
| 635 |
+
return out, logsumexp, max_scores
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
# Registers dispatches for SAC
|
| 639 |
+
redirect_to_mode(flex_attention, _CachingTorchDispatchMode)
|
| 640 |
+
redirect_to_mode(flex_attention, _CachedTorchDispatchMode)
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
# ---------------------------- Autograd Implementation ----------------------------
|
| 644 |
+
def create_fw_bw_graph(
|
| 645 |
+
score_mod: Callable,
|
| 646 |
+
index_values: tuple[Tensor, Tensor, Tensor, Tensor, Tensor],
|
| 647 |
+
other_buffers: tuple[Tensor, ...],
|
| 648 |
+
) -> tuple[Callable, Callable]:
|
| 649 |
+
# See Note:[HOP create fw_bw graph]
|
| 650 |
+
|
| 651 |
+
# All of these imports need to be here in order to avoid circular dependencies
|
| 652 |
+
from torch._dispatch.python import suspend_functionalization
|
| 653 |
+
from torch._functorch.aot_autograd import AOTConfig, create_joint
|
| 654 |
+
from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
|
| 655 |
+
from torch._subclasses.functional_tensor import disable_functional_mode
|
| 656 |
+
from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing
|
| 657 |
+
|
| 658 |
+
dummy_aot_config = AOTConfig(
|
| 659 |
+
fw_compiler=None, # type: ignore[arg-type]
|
| 660 |
+
bw_compiler=None, # type: ignore[arg-type]
|
| 661 |
+
partition_fn=None, # type: ignore[arg-type]
|
| 662 |
+
decompositions={},
|
| 663 |
+
num_params_buffers=0,
|
| 664 |
+
aot_id=0,
|
| 665 |
+
keep_inference_input_mutations=False,
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
with suspend_functionalization(), disable_functional_mode():
|
| 669 |
+
with disable_proxy_modes_tracing():
|
| 670 |
+
|
| 671 |
+
def _from_fun(
|
| 672 |
+
t: Tensor | torch.SymInt | int,
|
| 673 |
+
) -> Tensor | torch.SymInt | int:
|
| 674 |
+
if isinstance(t, torch.Tensor):
|
| 675 |
+
return torch.empty_strided(
|
| 676 |
+
t.size(),
|
| 677 |
+
t.stride(),
|
| 678 |
+
device=t.device,
|
| 679 |
+
dtype=t.dtype,
|
| 680 |
+
requires_grad=t.requires_grad,
|
| 681 |
+
)
|
| 682 |
+
return t
|
| 683 |
+
|
| 684 |
+
# If someone runs this hop under the default compiler backend ("eager")
|
| 685 |
+
# Then this path will be run with the actual user inputs. We convert them
|
| 686 |
+
# to fake tensors in order to not perform any actual compute.
|
| 687 |
+
from torch._guards import detect_fake_mode
|
| 688 |
+
|
| 689 |
+
fake_mode = detect_fake_mode(index_values)
|
| 690 |
+
if fake_mode is None:
|
| 691 |
+
fake_mode = FakeTensorMode(allow_non_fake_inputs=True)
|
| 692 |
+
|
| 693 |
+
with fake_mode:
|
| 694 |
+
unwrapped_score_mod_indexes = pytree.tree_map(_from_fun, index_values)
|
| 695 |
+
unwrapped_other_buffers = pytree.tree_map(_from_fun, other_buffers)
|
| 696 |
+
|
| 697 |
+
if not all(
|
| 698 |
+
isinstance(t, (FakeTensor, int, torch.SymInt))
|
| 699 |
+
for t in unwrapped_score_mod_indexes + unwrapped_other_buffers
|
| 700 |
+
):
|
| 701 |
+
raise AssertionError(
|
| 702 |
+
f"all unwrapped values must be FakeTensor, int, or SymInt, got "
|
| 703 |
+
f"{[type(t) for t in unwrapped_score_mod_indexes + unwrapped_other_buffers]}"
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
example_flat_out = pytree.tree_map(
|
| 707 |
+
_from_fun,
|
| 708 |
+
score_mod(*unwrapped_score_mod_indexes, *unwrapped_other_buffers),
|
| 709 |
+
)
|
| 710 |
+
if not isinstance(example_flat_out, torch.Tensor):
|
| 711 |
+
raise RuntimeError(
|
| 712 |
+
"Expected output of score_mod to be a tensor."
|
| 713 |
+
f"Got type {type(example_flat_out)}."
|
| 714 |
+
)
|
| 715 |
+
example_grad = _from_fun(example_flat_out)
|
| 716 |
+
|
| 717 |
+
def joint_f(
|
| 718 |
+
score: Tensor,
|
| 719 |
+
b: Tensor,
|
| 720 |
+
h: Tensor,
|
| 721 |
+
m: Tensor,
|
| 722 |
+
n: Tensor,
|
| 723 |
+
example_grad: Tensor,
|
| 724 |
+
*other_buffers: tuple[Tensor, ...],
|
| 725 |
+
) -> tuple[Tensor, ...]:
|
| 726 |
+
def fw_with_masks(
|
| 727 |
+
*args: tuple[Tensor, ...],
|
| 728 |
+
) -> tuple[tuple[Tensor], tuple[bool]]:
|
| 729 |
+
fw_out = score_mod(*args)
|
| 730 |
+
out_requires_grad = fw_out.requires_grad
|
| 731 |
+
return ((fw_out,), (out_requires_grad,))
|
| 732 |
+
|
| 733 |
+
joint = create_joint(fw_with_masks, aot_config=dummy_aot_config)
|
| 734 |
+
args = [score, b, h, m, n] + list(other_buffers)
|
| 735 |
+
optional_grad = [example_grad] if example_grad.requires_grad else []
|
| 736 |
+
_, grads = joint(args, optional_grad)
|
| 737 |
+
|
| 738 |
+
return grads
|
| 739 |
+
|
| 740 |
+
joint_graph = make_fx(joint_f)(
|
| 741 |
+
*unwrapped_score_mod_indexes, example_grad, *unwrapped_other_buffers
|
| 742 |
+
)
|
| 743 |
+
# pyrefly: ignore [bad-return]
|
| 744 |
+
return score_mod, joint_graph
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
class FlexAttentionAutogradOp(torch.autograd.Function):
|
| 748 |
+
@staticmethod
|
| 749 |
+
# pyrefly: ignore [bad-override]
|
| 750 |
+
def forward(
|
| 751 |
+
ctx: Any,
|
| 752 |
+
query: Tensor,
|
| 753 |
+
key: Tensor,
|
| 754 |
+
value: Tensor,
|
| 755 |
+
fw_graph: Callable,
|
| 756 |
+
joint_graph: Callable,
|
| 757 |
+
block_mask: tuple[Any, ...],
|
| 758 |
+
scale: float,
|
| 759 |
+
kernel_options: dict[str, Any],
|
| 760 |
+
mask_mod_other_buffers: tuple[Any, ...],
|
| 761 |
+
*score_mod_other_buffers: tuple[Any, ...],
|
| 762 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 763 |
+
ctx.set_materialize_grads(False)
|
| 764 |
+
any_buffer_requires_grad = any(
|
| 765 |
+
buffer.requires_grad
|
| 766 |
+
for buffer in mask_mod_other_buffers
|
| 767 |
+
if isinstance(buffer, torch.Tensor)
|
| 768 |
+
)
|
| 769 |
+
if any_buffer_requires_grad:
|
| 770 |
+
raise AssertionError(
|
| 771 |
+
"Captured buffers from mask mod that require grad are not supported."
|
| 772 |
+
)
|
| 773 |
+
ctx._fw_graph = fw_graph
|
| 774 |
+
ctx._joint_graph = joint_graph
|
| 775 |
+
ctx._mask_graph = block_mask[-1]
|
| 776 |
+
ctx.scale = scale
|
| 777 |
+
ctx.kernel_options = kernel_options
|
| 778 |
+
ctx._score_mod_other_buffers_len = len(score_mod_other_buffers)
|
| 779 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 780 |
+
out, logsumexp, max_scores = flex_attention(
|
| 781 |
+
query,
|
| 782 |
+
key,
|
| 783 |
+
value,
|
| 784 |
+
fw_graph,
|
| 785 |
+
block_mask,
|
| 786 |
+
scale,
|
| 787 |
+
kernel_options,
|
| 788 |
+
score_mod_other_buffers,
|
| 789 |
+
mask_mod_other_buffers,
|
| 790 |
+
)
|
| 791 |
+
# no grads for you sir
|
| 792 |
+
ctx.mark_non_differentiable(max_scores)
|
| 793 |
+
save_values_for_backward(
|
| 794 |
+
ctx,
|
| 795 |
+
(
|
| 796 |
+
query,
|
| 797 |
+
key,
|
| 798 |
+
value,
|
| 799 |
+
out,
|
| 800 |
+
logsumexp,
|
| 801 |
+
max_scores,
|
| 802 |
+
*block_mask[:-1],
|
| 803 |
+
*score_mod_other_buffers,
|
| 804 |
+
*mask_mod_other_buffers,
|
| 805 |
+
),
|
| 806 |
+
)
|
| 807 |
+
return out, logsumexp, max_scores
|
| 808 |
+
|
| 809 |
+
@staticmethod
|
| 810 |
+
def backward( # type: ignore[override]
|
| 811 |
+
ctx: Any,
|
| 812 |
+
grad_out: Tensor,
|
| 813 |
+
grad_logsumexp: Tensor,
|
| 814 |
+
grad_max_scores: Tensor,
|
| 815 |
+
) -> tuple[Tensor | None, ...]:
|
| 816 |
+
fw_args = saved_values(ctx)
|
| 817 |
+
(
|
| 818 |
+
query,
|
| 819 |
+
key,
|
| 820 |
+
value,
|
| 821 |
+
out,
|
| 822 |
+
logsumexp,
|
| 823 |
+
max_scores,
|
| 824 |
+
query_lengths,
|
| 825 |
+
kv_lengths,
|
| 826 |
+
kv_num_blocks,
|
| 827 |
+
kv_indices,
|
| 828 |
+
full_kv_num_blocks,
|
| 829 |
+
full_kv_indices,
|
| 830 |
+
q_num_blocks,
|
| 831 |
+
q_indices,
|
| 832 |
+
full_q_num_blocks,
|
| 833 |
+
full_q_indices,
|
| 834 |
+
Q_BLOCK_SIZE,
|
| 835 |
+
KV_BLOCK_SIZE,
|
| 836 |
+
*other_buffers,
|
| 837 |
+
) = fw_args
|
| 838 |
+
fw_graph = ctx._fw_graph
|
| 839 |
+
joint_graph = ctx._joint_graph
|
| 840 |
+
mask_graph = ctx._mask_graph
|
| 841 |
+
scale = ctx.scale
|
| 842 |
+
kernel_options = ctx.kernel_options
|
| 843 |
+
score_mod_other_buffers = tuple(
|
| 844 |
+
other_buffers[: ctx._score_mod_other_buffers_len]
|
| 845 |
+
)
|
| 846 |
+
mask_mod_other_buffers = tuple(
|
| 847 |
+
other_buffers[ctx._score_mod_other_buffers_len :]
|
| 848 |
+
)
|
| 849 |
+
# We have asserted that mask_mod_other_buffers do not require grad,
|
| 850 |
+
# but score_mod_other_buffers can require grad.
|
| 851 |
+
none_grads = [None] * 6
|
| 852 |
+
(
|
| 853 |
+
grad_query,
|
| 854 |
+
grad_key,
|
| 855 |
+
grad_value,
|
| 856 |
+
grad_score_mod_captured,
|
| 857 |
+
) = flex_attention_backward(
|
| 858 |
+
query,
|
| 859 |
+
key,
|
| 860 |
+
value,
|
| 861 |
+
out,
|
| 862 |
+
logsumexp,
|
| 863 |
+
grad_out,
|
| 864 |
+
grad_logsumexp,
|
| 865 |
+
fw_graph,
|
| 866 |
+
joint_graph,
|
| 867 |
+
(
|
| 868 |
+
query_lengths,
|
| 869 |
+
kv_lengths,
|
| 870 |
+
kv_num_blocks,
|
| 871 |
+
kv_indices,
|
| 872 |
+
full_kv_num_blocks,
|
| 873 |
+
full_kv_indices,
|
| 874 |
+
q_num_blocks,
|
| 875 |
+
q_indices,
|
| 876 |
+
full_q_num_blocks,
|
| 877 |
+
full_q_indices,
|
| 878 |
+
Q_BLOCK_SIZE,
|
| 879 |
+
KV_BLOCK_SIZE,
|
| 880 |
+
mask_graph,
|
| 881 |
+
),
|
| 882 |
+
scale,
|
| 883 |
+
kernel_options,
|
| 884 |
+
score_mod_other_buffers,
|
| 885 |
+
mask_mod_other_buffers,
|
| 886 |
+
)
|
| 887 |
+
return grad_query, grad_key, grad_value, *none_grads, *grad_score_mod_captured
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
# TODO: Rework DispatchKey.Autograd to py_autograd_impl
|
| 891 |
+
@flex_attention.py_impl(DispatchKey.Autograd)
|
| 892 |
+
def flex_attention_autograd(
|
| 893 |
+
query: torch.Tensor,
|
| 894 |
+
key: torch.Tensor,
|
| 895 |
+
value: torch.Tensor,
|
| 896 |
+
score_mod: Callable,
|
| 897 |
+
block_mask: tuple,
|
| 898 |
+
scale: float,
|
| 899 |
+
kernel_options: dict[str, Any],
|
| 900 |
+
score_mod_other_buffers: tuple[Tensor, ...] = (),
|
| 901 |
+
mask_mod_other_buffers: tuple[Tensor, ...] = (),
|
| 902 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 903 |
+
from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
|
| 904 |
+
|
| 905 |
+
with TransformGetItemToIndex():
|
| 906 |
+
input_requires_grad = any(
|
| 907 |
+
isinstance(t, torch.Tensor) and t.requires_grad
|
| 908 |
+
for t in (query, key, value, *score_mod_other_buffers)
|
| 909 |
+
)
|
| 910 |
+
if torch.is_grad_enabled() and input_requires_grad:
|
| 911 |
+
if block_mask[7] is None:
|
| 912 |
+
raise RuntimeError(
|
| 913 |
+
"BlockMask q_indices is None. Backward pass requires q_indices to be computed. "
|
| 914 |
+
"Please create the BlockMask with compute_q_blocks=True"
|
| 915 |
+
)
|
| 916 |
+
example_vals = (
|
| 917 |
+
query.new_zeros((), requires_grad=input_requires_grad),
|
| 918 |
+
query.new_zeros((), dtype=torch.int),
|
| 919 |
+
query.new_zeros((), dtype=torch.int),
|
| 920 |
+
query.new_zeros((), dtype=torch.int),
|
| 921 |
+
query.new_zeros((), dtype=torch.int),
|
| 922 |
+
)
|
| 923 |
+
fw_graph, bw_graph = create_fw_bw_graph(
|
| 924 |
+
score_mod, example_vals, score_mod_other_buffers
|
| 925 |
+
)
|
| 926 |
+
else:
|
| 927 |
+
fw_graph, bw_graph = score_mod, None
|
| 928 |
+
out, logsumexp, max_scores = FlexAttentionAutogradOp.apply(
|
| 929 |
+
query,
|
| 930 |
+
key,
|
| 931 |
+
value,
|
| 932 |
+
fw_graph,
|
| 933 |
+
bw_graph,
|
| 934 |
+
block_mask,
|
| 935 |
+
scale,
|
| 936 |
+
kernel_options,
|
| 937 |
+
mask_mod_other_buffers,
|
| 938 |
+
*score_mod_other_buffers,
|
| 939 |
+
)
|
| 940 |
+
return out, logsumexp, max_scores
|
| 941 |
+
|
| 942 |
+
|
| 943 |
+
# ---------------------------- Backward HOP Implementation ----------------------------
|
| 944 |
+
|
| 945 |
+
|
| 946 |
+
@flex_attention_backward.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 947 |
+
def sdpa_dense_backward(
|
| 948 |
+
query: torch.Tensor,
|
| 949 |
+
key: torch.Tensor,
|
| 950 |
+
value: torch.Tensor,
|
| 951 |
+
out: torch.Tensor,
|
| 952 |
+
logsumexp: torch.Tensor,
|
| 953 |
+
grad_out: torch.Tensor | None,
|
| 954 |
+
grad_logsumexp: torch.Tensor | None,
|
| 955 |
+
fw_graph: Callable, # GraphModule type hint?
|
| 956 |
+
joint_graph: Callable,
|
| 957 |
+
block_mask: tuple,
|
| 958 |
+
scale: float,
|
| 959 |
+
kernel_options: dict[str, Any],
|
| 960 |
+
score_mod_other_buffers: tuple,
|
| 961 |
+
mask_mod_other_buffers: tuple,
|
| 962 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]:
|
| 963 |
+
if query.dtype != key.dtype or query.dtype != value.dtype:
|
| 964 |
+
raise ValueError(
|
| 965 |
+
f"Backward pass with mixed query, key, and value dtype is not supported, "
|
| 966 |
+
f"got query.dtype={query.dtype}, key.dtype={key.dtype}, "
|
| 967 |
+
f"and value.dtype={value.dtype}"
|
| 968 |
+
)
|
| 969 |
+
if joint_graph is None:
|
| 970 |
+
example_vals = (
|
| 971 |
+
query.new_zeros((), requires_grad=True),
|
| 972 |
+
query.new_zeros((), dtype=torch.int),
|
| 973 |
+
query.new_zeros((), dtype=torch.int),
|
| 974 |
+
query.new_zeros((), dtype=torch.int),
|
| 975 |
+
query.new_zeros((), dtype=torch.int),
|
| 976 |
+
)
|
| 977 |
+
_, joint_graph = create_fw_bw_graph(
|
| 978 |
+
fw_graph, example_vals, score_mod_other_buffers
|
| 979 |
+
)
|
| 980 |
+
from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
|
| 981 |
+
|
| 982 |
+
Bq, Hq, seq_len_q, qk_head_dim = query.shape
|
| 983 |
+
Bkv, Hkv, seq_len_kv, v_head_dim = value.shape
|
| 984 |
+
|
| 985 |
+
# Get outputs before calling repeat interleave and permute to input stride orders
|
| 986 |
+
actual_grad_query = query.new_empty((Bq, Hq, seq_len_q, qk_head_dim))
|
| 987 |
+
actual_grad_query = _permute_strides(actual_grad_query, query.stride())
|
| 988 |
+
|
| 989 |
+
actual_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim))
|
| 990 |
+
actual_grad_key = _permute_strides(actual_grad_key, key.stride())
|
| 991 |
+
|
| 992 |
+
actual_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim))
|
| 993 |
+
actual_grad_value = _permute_strides(actual_grad_value, value.stride())
|
| 994 |
+
|
| 995 |
+
def _maybe_new_buffer(
|
| 996 |
+
buffer: torch.Tensor | torch.SymInt | int,
|
| 997 |
+
) -> torch.Tensor | torch.SymInt | int | None:
|
| 998 |
+
if isinstance(buffer, torch.Tensor):
|
| 999 |
+
return (
|
| 1000 |
+
torch.empty_like(buffer, memory_format=torch.contiguous_format)
|
| 1001 |
+
if buffer.requires_grad
|
| 1002 |
+
else None
|
| 1003 |
+
)
|
| 1004 |
+
return buffer
|
| 1005 |
+
|
| 1006 |
+
actual_grad_score_mod_captured = [
|
| 1007 |
+
_maybe_new_buffer(buffer) for buffer in score_mod_other_buffers
|
| 1008 |
+
]
|
| 1009 |
+
|
| 1010 |
+
Bq, Bkv = query.size(0), key.size(0)
|
| 1011 |
+
if not ((Bq == Bkv) or (Bq > 1 and Bkv == 1)):
|
| 1012 |
+
raise RuntimeError(f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}")
|
| 1013 |
+
|
| 1014 |
+
key = key.expand((Bq, *key.size()[1:]))
|
| 1015 |
+
value = value.expand((Bq, *value.size()[1:]))
|
| 1016 |
+
|
| 1017 |
+
G = query.size(1) // key.size(1)
|
| 1018 |
+
key = torch.repeat_interleave(key, G, dim=1)
|
| 1019 |
+
value = torch.repeat_interleave(value, G, dim=1)
|
| 1020 |
+
|
| 1021 |
+
if grad_out is None:
|
| 1022 |
+
grad_out = torch.zeros_like(out)
|
| 1023 |
+
if grad_logsumexp is None:
|
| 1024 |
+
grad_logsumexp = torch.zeros_like(logsumexp)
|
| 1025 |
+
|
| 1026 |
+
# logsumexp is expected in log2 scale (as returned by the forward HOP).
|
| 1027 |
+
# The public flex_attention API converts lse to natural log before returning,
|
| 1028 |
+
# so callers using the public API must not pass that value here directly.
|
| 1029 |
+
logsumexp = logsumexp * math.log(2)
|
| 1030 |
+
# The backwards formula for the log -> log2 change of base in the forwards
|
| 1031 |
+
grad_logsumexp = grad_logsumexp / math.log(2)
|
| 1032 |
+
scores, post_mod_scores = _math_attention_inner(
|
| 1033 |
+
query,
|
| 1034 |
+
key,
|
| 1035 |
+
value,
|
| 1036 |
+
fw_graph,
|
| 1037 |
+
block_mask,
|
| 1038 |
+
scale,
|
| 1039 |
+
kernel_options,
|
| 1040 |
+
score_mod_other_buffers,
|
| 1041 |
+
mask_mod_other_buffers,
|
| 1042 |
+
)
|
| 1043 |
+
masked_out_rows = logsumexp == -float("inf")
|
| 1044 |
+
softmax_scores = torch.exp(post_mod_scores - logsumexp.unsqueeze(-1))
|
| 1045 |
+
softmax_scores = torch.where(masked_out_rows.unsqueeze(-1), 0, softmax_scores)
|
| 1046 |
+
|
| 1047 |
+
grad_value = softmax_scores.to(query.dtype).transpose(-2, -1) @ grad_out
|
| 1048 |
+
|
| 1049 |
+
grad_softmax_scores = grad_out.to(dtype=softmax_scores.dtype) @ value.to(
|
| 1050 |
+
dtype=softmax_scores.dtype
|
| 1051 |
+
).transpose(-2, -1)
|
| 1052 |
+
|
| 1053 |
+
sum_scores = torch.sum(
|
| 1054 |
+
out.to(dtype=softmax_scores.dtype) * grad_out.to(dtype=softmax_scores.dtype),
|
| 1055 |
+
-1,
|
| 1056 |
+
keepdim=True,
|
| 1057 |
+
)
|
| 1058 |
+
grad_score_mod = softmax_scores * (
|
| 1059 |
+
grad_softmax_scores - sum_scores + grad_logsumexp.unsqueeze(-1)
|
| 1060 |
+
)
|
| 1061 |
+
|
| 1062 |
+
b = torch.arange(0, scores.size(0), device=scores.device)
|
| 1063 |
+
h = torch.arange(0, scores.size(1), device=scores.device)
|
| 1064 |
+
m = torch.arange(0, scores.size(2), device=scores.device)
|
| 1065 |
+
n = torch.arange(0, scores.size(3), device=scores.device)
|
| 1066 |
+
|
| 1067 |
+
mask_graph = block_mask[-1]
|
| 1068 |
+
# Gradient of the inline score_mod function, with respect to the scores
|
| 1069 |
+
captured_buffers_in_dim = (None,) * len(score_mod_other_buffers)
|
| 1070 |
+
out_dims = [0, None, None, None, None] + [None] * len(score_mod_other_buffers)
|
| 1071 |
+
from torch.nn.attention.flex_attention import _vmap_for_bhqkv
|
| 1072 |
+
|
| 1073 |
+
# inputs are [score, b, h, q_idx, kv_idx, gradOut, ...]
|
| 1074 |
+
# score and gradOut are "fully" batched
|
| 1075 |
+
joint_score_mod = _vmap_for_bhqkv(
|
| 1076 |
+
joint_graph,
|
| 1077 |
+
prefix=(0,),
|
| 1078 |
+
suffix=(0,) + captured_buffers_in_dim,
|
| 1079 |
+
out_dims=out_dims,
|
| 1080 |
+
)
|
| 1081 |
+
with TransformGetItemToIndex():
|
| 1082 |
+
grad_scores, _, _, _, _, *grad_score_mod_captured = joint_score_mod(
|
| 1083 |
+
scores, b, h, m, n, grad_score_mod, *score_mod_other_buffers
|
| 1084 |
+
)
|
| 1085 |
+
grad_scores = grad_scores * scale
|
| 1086 |
+
grad_scores = grad_scores.to(query.dtype)
|
| 1087 |
+
|
| 1088 |
+
mask_mod = _vmap_for_bhqkv(
|
| 1089 |
+
mask_graph, prefix=(), suffix=(None,) * len(mask_mod_other_buffers)
|
| 1090 |
+
)
|
| 1091 |
+
with TransformGetItemToIndex():
|
| 1092 |
+
mask_scores = mask_mod(b, h, m, n, *mask_mod_other_buffers)
|
| 1093 |
+
grad_scores = torch.where(
|
| 1094 |
+
mask_scores, grad_scores, torch.tensor(0, dtype=query.dtype)
|
| 1095 |
+
)
|
| 1096 |
+
|
| 1097 |
+
grad_query = grad_scores @ key
|
| 1098 |
+
grad_key = grad_scores.transpose(-2, -1) @ query
|
| 1099 |
+
|
| 1100 |
+
# Reduce DK, DV along broadcasted heads.
|
| 1101 |
+
grad_key = grad_key.view(
|
| 1102 |
+
grad_key.size(0), -1, G, grad_key.size(-2), grad_key.size(-1)
|
| 1103 |
+
)
|
| 1104 |
+
grad_value = grad_value.view(
|
| 1105 |
+
grad_value.size(0), -1, G, grad_value.size(-2), grad_value.size(-1)
|
| 1106 |
+
)
|
| 1107 |
+
|
| 1108 |
+
grad_key = torch.sum(grad_key, 2, keepdim=False)
|
| 1109 |
+
grad_value = torch.sum(grad_value, 2, keepdim=False)
|
| 1110 |
+
|
| 1111 |
+
# Fill to correctly strided outputs
|
| 1112 |
+
actual_grad_query.copy_(grad_query)
|
| 1113 |
+
actual_grad_key.copy_(grad_key)
|
| 1114 |
+
actual_grad_value.copy_(grad_value)
|
| 1115 |
+
|
| 1116 |
+
if Bq != Bkv:
|
| 1117 |
+
if not (Bq > 1 and Bkv == 1):
|
| 1118 |
+
raise AssertionError(
|
| 1119 |
+
f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}"
|
| 1120 |
+
)
|
| 1121 |
+
|
| 1122 |
+
actual_grad_key = torch.sum(actual_grad_key, 0, keepdim=True)
|
| 1123 |
+
actual_grad_value = torch.sum(actual_grad_value, 0, keepdim=True)
|
| 1124 |
+
|
| 1125 |
+
score_mod_other_buffer_grads = [
|
| 1126 |
+
actual_grad.copy_(grad) if isinstance(actual_grad, torch.Tensor) else None
|
| 1127 |
+
for actual_grad, grad in zip(
|
| 1128 |
+
actual_grad_score_mod_captured, grad_score_mod_captured
|
| 1129 |
+
)
|
| 1130 |
+
]
|
| 1131 |
+
|
| 1132 |
+
return (
|
| 1133 |
+
actual_grad_query,
|
| 1134 |
+
actual_grad_key,
|
| 1135 |
+
actual_grad_value,
|
| 1136 |
+
tuple(score_mod_other_buffer_grads),
|
| 1137 |
+
)
|
| 1138 |
+
|
| 1139 |
+
|
| 1140 |
+
def trace_flex_attention_backward(
|
| 1141 |
+
proxy_mode: ProxyTorchDispatchMode,
|
| 1142 |
+
query: torch.Tensor,
|
| 1143 |
+
key: torch.Tensor,
|
| 1144 |
+
value: torch.Tensor,
|
| 1145 |
+
out: torch.Tensor,
|
| 1146 |
+
logsumexp: torch.Tensor,
|
| 1147 |
+
grad_out: torch.Tensor,
|
| 1148 |
+
grad_logsumexp: torch.Tensor,
|
| 1149 |
+
fw_graph: Callable | GraphModule,
|
| 1150 |
+
joint_graph: GraphModule,
|
| 1151 |
+
block_mask: tuple,
|
| 1152 |
+
scale: float,
|
| 1153 |
+
kernel_options: dict[str, Any],
|
| 1154 |
+
score_mod_other_buffers: tuple = (),
|
| 1155 |
+
mask_mod_other_buffers: tuple = (),
|
| 1156 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]:
|
| 1157 |
+
"""We already have the forward graph and joint graph from the forward pass, so we create a proxy attach both graphs"""
|
| 1158 |
+
from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
|
| 1159 |
+
|
| 1160 |
+
example_out = flex_attention_backward(
|
| 1161 |
+
query,
|
| 1162 |
+
key,
|
| 1163 |
+
value,
|
| 1164 |
+
out,
|
| 1165 |
+
logsumexp,
|
| 1166 |
+
grad_out,
|
| 1167 |
+
grad_logsumexp,
|
| 1168 |
+
fw_graph,
|
| 1169 |
+
joint_graph,
|
| 1170 |
+
block_mask,
|
| 1171 |
+
scale,
|
| 1172 |
+
kernel_options,
|
| 1173 |
+
score_mod_other_buffers,
|
| 1174 |
+
mask_mod_other_buffers,
|
| 1175 |
+
)
|
| 1176 |
+
|
| 1177 |
+
requires_grad = any(pytree.tree_map(lambda x: x.requires_grad, (query, key)))
|
| 1178 |
+
fw_example_vals = [query.new_zeros((), requires_grad=requires_grad)] + [
|
| 1179 |
+
query.new_zeros((), dtype=torch.int) for _ in range(4)
|
| 1180 |
+
]
|
| 1181 |
+
bw_example_vals = fw_example_vals + [query.new_zeros(())]
|
| 1182 |
+
mask_example_vals = [query.new_zeros((), dtype=torch.int) for _ in range(4)]
|
| 1183 |
+
mask_graph = block_mask[-1]
|
| 1184 |
+
with TransformGetItemToIndex():
|
| 1185 |
+
# There's no active make_fx during the compiled autograd graph's initial capture
|
| 1186 |
+
fw_graph = _maybe_reenter_make_fx(fw_graph)(
|
| 1187 |
+
*fw_example_vals, *score_mod_other_buffers
|
| 1188 |
+
)
|
| 1189 |
+
joint_graph = _maybe_reenter_make_fx(joint_graph)(
|
| 1190 |
+
*bw_example_vals, *score_mod_other_buffers
|
| 1191 |
+
)
|
| 1192 |
+
mask_graph = _maybe_reenter_make_fx(mask_graph)(
|
| 1193 |
+
*mask_example_vals, *mask_mod_other_buffers
|
| 1194 |
+
)
|
| 1195 |
+
if not isinstance(proxy_mode.tracer, torch.fx.Tracer):
|
| 1196 |
+
raise AssertionError(
|
| 1197 |
+
f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}"
|
| 1198 |
+
)
|
| 1199 |
+
block_mask = block_mask[:-1] + (mask_graph,)
|
| 1200 |
+
|
| 1201 |
+
qualname = proxy_mode.tracer.get_fresh_qualname("fw_graph")
|
| 1202 |
+
proxy_mode.tracer.root.register_module(qualname, fw_graph) # type: ignore[arg-type]
|
| 1203 |
+
qualname = proxy_mode.tracer.get_fresh_qualname("joint_graph")
|
| 1204 |
+
proxy_mode.tracer.root.register_module(qualname, joint_graph)
|
| 1205 |
+
qualname = proxy_mode.tracer.get_fresh_qualname("mask_graph")
|
| 1206 |
+
proxy_mode.tracer.root.register_module(qualname, mask_graph)
|
| 1207 |
+
|
| 1208 |
+
node_args = (
|
| 1209 |
+
query,
|
| 1210 |
+
key,
|
| 1211 |
+
value,
|
| 1212 |
+
out,
|
| 1213 |
+
logsumexp,
|
| 1214 |
+
grad_out,
|
| 1215 |
+
grad_logsumexp,
|
| 1216 |
+
fw_graph,
|
| 1217 |
+
joint_graph,
|
| 1218 |
+
block_mask,
|
| 1219 |
+
scale,
|
| 1220 |
+
kernel_options,
|
| 1221 |
+
score_mod_other_buffers,
|
| 1222 |
+
mask_mod_other_buffers,
|
| 1223 |
+
)
|
| 1224 |
+
# pyrefly: ignore [missing-attribute]
|
| 1225 |
+
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
|
| 1226 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 1227 |
+
"call_function",
|
| 1228 |
+
flex_attention_backward,
|
| 1229 |
+
proxy_args,
|
| 1230 |
+
{},
|
| 1231 |
+
name="flex_attention_backward",
|
| 1232 |
+
)
|
| 1233 |
+
return track_tensor_tree(
|
| 1234 |
+
example_out,
|
| 1235 |
+
out_proxy,
|
| 1236 |
+
constant=None,
|
| 1237 |
+
tracer=proxy_mode.tracer,
|
| 1238 |
+
)
|
| 1239 |
+
|
| 1240 |
+
|
| 1241 |
+
@flex_attention_backward.py_impl(ProxyTorchDispatchMode)
|
| 1242 |
+
def flex_attention_backward_proxy_torch_dispatch_mode(
|
| 1243 |
+
mode: ProxyTorchDispatchMode,
|
| 1244 |
+
query: torch.Tensor,
|
| 1245 |
+
key: torch.Tensor,
|
| 1246 |
+
value: torch.Tensor,
|
| 1247 |
+
out: torch.Tensor,
|
| 1248 |
+
logsumexp: torch.Tensor,
|
| 1249 |
+
grad_out: torch.Tensor,
|
| 1250 |
+
grad_logsumexp: torch.Tensor,
|
| 1251 |
+
fw_graph: Callable | GraphModule,
|
| 1252 |
+
joint_graph: GraphModule,
|
| 1253 |
+
block_mask: tuple,
|
| 1254 |
+
scale: float,
|
| 1255 |
+
kernel_options: dict[str, Any],
|
| 1256 |
+
score_mod_other_buffers: tuple = (),
|
| 1257 |
+
mask_mod_other_buffers: tuple = (),
|
| 1258 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]:
|
| 1259 |
+
if mode is None:
|
| 1260 |
+
raise AssertionError("Mode should always be enabled for python fallback key")
|
| 1261 |
+
with torch.fx.experimental.proxy_tensor.set_original_aten_op(
|
| 1262 |
+
flex_attention_backward
|
| 1263 |
+
):
|
| 1264 |
+
return trace_flex_attention_backward(
|
| 1265 |
+
mode,
|
| 1266 |
+
query,
|
| 1267 |
+
key,
|
| 1268 |
+
value,
|
| 1269 |
+
out,
|
| 1270 |
+
logsumexp,
|
| 1271 |
+
grad_out,
|
| 1272 |
+
grad_logsumexp,
|
| 1273 |
+
fw_graph,
|
| 1274 |
+
joint_graph,
|
| 1275 |
+
block_mask,
|
| 1276 |
+
scale,
|
| 1277 |
+
kernel_options,
|
| 1278 |
+
score_mod_other_buffers,
|
| 1279 |
+
mask_mod_other_buffers,
|
| 1280 |
+
)
|
| 1281 |
+
|
| 1282 |
+
|
| 1283 |
+
@flex_attention_backward.py_functionalize_impl
|
| 1284 |
+
def flex_attention_backward_functionalize(
|
| 1285 |
+
ctx: torch._subclasses.functional_tensor.BaseFunctionalizeAPI,
|
| 1286 |
+
query: torch.Tensor,
|
| 1287 |
+
key: torch.Tensor,
|
| 1288 |
+
value: torch.Tensor,
|
| 1289 |
+
out: torch.Tensor,
|
| 1290 |
+
logsumexp: torch.Tensor,
|
| 1291 |
+
grad_out: torch.Tensor,
|
| 1292 |
+
grad_logsumexp: torch.Tensor,
|
| 1293 |
+
fw_graph: Callable | GraphModule,
|
| 1294 |
+
joint_graph: GraphModule,
|
| 1295 |
+
block_mask: tuple,
|
| 1296 |
+
scale: float,
|
| 1297 |
+
kernel_options: dict[str, Any],
|
| 1298 |
+
score_mod_other_buffers: tuple = (),
|
| 1299 |
+
mask_mod_other_buffers: tuple = (),
|
| 1300 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]:
|
| 1301 |
+
"""Defines the functionalization rules for the flex_attention operator.
|
| 1302 |
+
|
| 1303 |
+
Write now we are unwrapping each tensor and then redispatching to the next,
|
| 1304 |
+
since we know that the forward score mod function is assured to be free of mutations
|
| 1305 |
+
to the other_buffers, we skip that mutate check and go straight to redispatching.
|
| 1306 |
+
"""
|
| 1307 |
+
|
| 1308 |
+
query_unwrapped = ctx.unwrap_tensors(query)
|
| 1309 |
+
key_unwrapped = ctx.unwrap_tensors(key)
|
| 1310 |
+
value_unwrapped = ctx.unwrap_tensors(value)
|
| 1311 |
+
out_unwrapped = ctx.unwrap_tensors(out)
|
| 1312 |
+
logsumexp_unwrapped = ctx.unwrap_tensors(logsumexp)
|
| 1313 |
+
grad_out_unwrapped = ctx.unwrap_tensors(grad_out)
|
| 1314 |
+
grad_logsumexp_unwrapped = ctx.unwrap_tensors(grad_logsumexp)
|
| 1315 |
+
block_mask_unwrapped = ctx.unwrap_tensors(block_mask)
|
| 1316 |
+
score_mod_other_buffers_unwrapped = ctx.unwrap_tensors(score_mod_other_buffers)
|
| 1317 |
+
mask_mod_other_buffers_unwrapped = ctx.unwrap_tensors(mask_mod_other_buffers)
|
| 1318 |
+
|
| 1319 |
+
# Appease the mypy overlords
|
| 1320 |
+
if not isinstance(query_unwrapped, torch.Tensor):
|
| 1321 |
+
raise AssertionError(
|
| 1322 |
+
f"expected query_unwrapped to be torch.Tensor, got {type(query_unwrapped)}"
|
| 1323 |
+
)
|
| 1324 |
+
if not isinstance(key_unwrapped, torch.Tensor):
|
| 1325 |
+
raise AssertionError(
|
| 1326 |
+
f"expected key_unwrapped to be torch.Tensor, got {type(key_unwrapped)}"
|
| 1327 |
+
)
|
| 1328 |
+
if not isinstance(value_unwrapped, torch.Tensor):
|
| 1329 |
+
raise AssertionError(
|
| 1330 |
+
f"expected value_unwrapped to be torch.Tensor, got {type(value_unwrapped)}"
|
| 1331 |
+
)
|
| 1332 |
+
if not isinstance(out_unwrapped, torch.Tensor):
|
| 1333 |
+
raise AssertionError(
|
| 1334 |
+
f"expected out_unwrapped to be torch.Tensor, got {type(out_unwrapped)}"
|
| 1335 |
+
)
|
| 1336 |
+
if not isinstance(logsumexp_unwrapped, torch.Tensor):
|
| 1337 |
+
raise AssertionError(
|
| 1338 |
+
f"expected logsumexp_unwrapped to be torch.Tensor, got {type(logsumexp_unwrapped)}"
|
| 1339 |
+
)
|
| 1340 |
+
if grad_out_unwrapped is not None and not isinstance(
|
| 1341 |
+
grad_out_unwrapped, torch.Tensor
|
| 1342 |
+
):
|
| 1343 |
+
raise AssertionError(
|
| 1344 |
+
f"expected grad_out_unwrapped to be torch.Tensor or None, got {type(grad_out_unwrapped)}"
|
| 1345 |
+
)
|
| 1346 |
+
if grad_logsumexp_unwrapped is not None and not isinstance(
|
| 1347 |
+
grad_logsumexp_unwrapped, torch.Tensor
|
| 1348 |
+
):
|
| 1349 |
+
raise AssertionError(
|
| 1350 |
+
f"expected grad_logsumexp_unwrapped to be torch.Tensor or None, got {type(grad_logsumexp_unwrapped)}"
|
| 1351 |
+
)
|
| 1352 |
+
if not isinstance(block_mask_unwrapped, tuple):
|
| 1353 |
+
raise AssertionError(
|
| 1354 |
+
f"expected block_mask_unwrapped to be tuple, got {type(block_mask_unwrapped)}"
|
| 1355 |
+
)
|
| 1356 |
+
if not isinstance(score_mod_other_buffers_unwrapped, tuple):
|
| 1357 |
+
raise AssertionError(
|
| 1358 |
+
f"expected score_mod_other_buffers_unwrapped to be tuple, got {type(score_mod_other_buffers_unwrapped)}"
|
| 1359 |
+
)
|
| 1360 |
+
if not isinstance(mask_mod_other_buffers_unwrapped, tuple):
|
| 1361 |
+
raise AssertionError(
|
| 1362 |
+
f"expected mask_mod_other_buffers_unwrapped to be tuple, got {type(mask_mod_other_buffers_unwrapped)}"
|
| 1363 |
+
)
|
| 1364 |
+
|
| 1365 |
+
with ctx.redispatch_to_next():
|
| 1366 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1367 |
+
functional_fw_graph = ctx.functionalize(fw_graph)
|
| 1368 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1369 |
+
functional_joint_graph = ctx.functionalize(joint_graph)
|
| 1370 |
+
|
| 1371 |
+
(
|
| 1372 |
+
grad_query,
|
| 1373 |
+
grad_key,
|
| 1374 |
+
grad_value,
|
| 1375 |
+
grad_score_mod_captured,
|
| 1376 |
+
) = flex_attention_backward(
|
| 1377 |
+
query_unwrapped,
|
| 1378 |
+
key_unwrapped,
|
| 1379 |
+
value_unwrapped,
|
| 1380 |
+
out_unwrapped,
|
| 1381 |
+
logsumexp_unwrapped,
|
| 1382 |
+
grad_out_unwrapped,
|
| 1383 |
+
grad_logsumexp_unwrapped,
|
| 1384 |
+
functional_fw_graph, # type: ignore[arg-type]
|
| 1385 |
+
functional_joint_graph, # type: ignore[arg-type]
|
| 1386 |
+
block_mask_unwrapped,
|
| 1387 |
+
scale,
|
| 1388 |
+
kernel_options,
|
| 1389 |
+
score_mod_other_buffers_unwrapped,
|
| 1390 |
+
mask_mod_other_buffers_unwrapped,
|
| 1391 |
+
)
|
| 1392 |
+
|
| 1393 |
+
return ctx.wrap_tensors((grad_query, grad_key, grad_value, grad_score_mod_captured)) # type: ignore[return-value,arg-type]
|
| 1394 |
+
|
| 1395 |
+
|
| 1396 |
+
@register_fake(flex_attention_backward)
|
| 1397 |
+
def flex_attention_backward_fake_tensor_mode(
|
| 1398 |
+
query: torch.Tensor,
|
| 1399 |
+
key: torch.Tensor,
|
| 1400 |
+
value: torch.Tensor,
|
| 1401 |
+
out: torch.Tensor,
|
| 1402 |
+
logsumexp: torch.Tensor,
|
| 1403 |
+
grad_out: torch.Tensor,
|
| 1404 |
+
grad_logsumexp: torch.Tensor,
|
| 1405 |
+
fw_graph: Callable | GraphModule,
|
| 1406 |
+
joint_graph: GraphModule,
|
| 1407 |
+
block_mask: tuple,
|
| 1408 |
+
scale: float,
|
| 1409 |
+
kernel_options: dict[str, Any],
|
| 1410 |
+
score_mod_other_buffers: tuple = (),
|
| 1411 |
+
mask_mod_other_buffers: tuple = (),
|
| 1412 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]:
|
| 1413 |
+
if has_user_subclass(
|
| 1414 |
+
(
|
| 1415 |
+
query,
|
| 1416 |
+
key,
|
| 1417 |
+
value,
|
| 1418 |
+
out,
|
| 1419 |
+
logsumexp,
|
| 1420 |
+
grad_out,
|
| 1421 |
+
grad_logsumexp,
|
| 1422 |
+
block_mask,
|
| 1423 |
+
scale,
|
| 1424 |
+
kernel_options,
|
| 1425 |
+
score_mod_other_buffers,
|
| 1426 |
+
mask_mod_other_buffers,
|
| 1427 |
+
),
|
| 1428 |
+
allowed_subclasses=(FakeTensor,),
|
| 1429 |
+
):
|
| 1430 |
+
return NotImplemented
|
| 1431 |
+
Bq, _, _, qk_head_dim = query.shape
|
| 1432 |
+
Bkv, Hkv, seq_len_kv, v_head_dim = value.shape
|
| 1433 |
+
|
| 1434 |
+
grad_query = query.new_empty(query.shape)
|
| 1435 |
+
grad_query = _permute_strides(grad_query, query.stride())
|
| 1436 |
+
# zeros_and_scatter creates a contiguous zeros tensor -> contiguous_format
|
| 1437 |
+
grad_score_mod_captured = tuple(
|
| 1438 |
+
(
|
| 1439 |
+
torch.empty_like(buffer, memory_format=torch.contiguous_format)
|
| 1440 |
+
if isinstance(buffer, torch.Tensor)
|
| 1441 |
+
else None
|
| 1442 |
+
)
|
| 1443 |
+
for buffer in score_mod_other_buffers
|
| 1444 |
+
)
|
| 1445 |
+
|
| 1446 |
+
broadcasted_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim))
|
| 1447 |
+
broadcasted_grad_key = _permute_strides(broadcasted_grad_key, key.stride())
|
| 1448 |
+
|
| 1449 |
+
broadcasted_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim))
|
| 1450 |
+
broadcasted_grad_value = _permute_strides(broadcasted_grad_value, value.stride())
|
| 1451 |
+
|
| 1452 |
+
if Bq > 1 and Bkv == 1:
|
| 1453 |
+
grad_key = torch.sum(broadcasted_grad_key, dim=0, keepdim=True)
|
| 1454 |
+
grad_value = torch.sum(broadcasted_grad_value, dim=0, keepdim=True)
|
| 1455 |
+
else:
|
| 1456 |
+
grad_key = broadcasted_grad_key
|
| 1457 |
+
grad_value = broadcasted_grad_value
|
| 1458 |
+
|
| 1459 |
+
return grad_query, grad_key, grad_value, grad_score_mod_captured
|
| 1460 |
+
|
| 1461 |
+
|
| 1462 |
+
flex_attention_backward.py_autograd_impl(
|
| 1463 |
+
autograd_not_implemented(flex_attention_backward, deferred_error=True)
|
| 1464 |
+
)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/foreach_map.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
from collections.abc import Callable
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from torch._higher_order_ops.base_hop import BaseHOP, FunctionWithNoFreeVars
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ForeachMap(BaseHOP):
|
| 10 |
+
def __init__(self):
|
| 11 |
+
super().__init__("foreach_map")
|
| 12 |
+
|
| 13 |
+
def __call__(self, fn, *operands, **kwargs): # type: ignore[override]
|
| 14 |
+
fn = FunctionWithNoFreeVars(fn)
|
| 15 |
+
return super().__call__(fn, *operands, **kwargs)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
_foreach_map = ForeachMap()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def foreach_map(op: Callable, *operands: Any, **kwargs: dict[str, Any]):
|
| 22 |
+
from torch._dynamo.polyfills import foreach_map_fn
|
| 23 |
+
|
| 24 |
+
return _foreach_map(foreach_map_fn, op, *operands, **kwargs)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/hints_wrap.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch.utils._pytree as pytree
|
| 4 |
+
from torch._C import DispatchKey
|
| 5 |
+
from torch._higher_order_ops.utils import (
|
| 6 |
+
autograd_not_implemented,
|
| 7 |
+
reenter_make_fx,
|
| 8 |
+
unique_graph_id,
|
| 9 |
+
)
|
| 10 |
+
from torch._ops import HigherOrderOperator
|
| 11 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 12 |
+
from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# used for wrapping a function/op with context hints
|
| 16 |
+
class HintsWrapper(HigherOrderOperator):
|
| 17 |
+
def __init__(self):
|
| 18 |
+
super().__init__("hints_wrapper")
|
| 19 |
+
|
| 20 |
+
def __call__(self, body_fn, args, kwargs, hints):
|
| 21 |
+
r"""
|
| 22 |
+
Call implementation of hints_wrapper
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
body_fn (Callable): A callable function that is within the scope
|
| 26 |
+
that is being traced.
|
| 27 |
+
|
| 28 |
+
args (Tuple of torch.Tensor/int/float/bool): A tuple of inputs to
|
| 29 |
+
body_fn.
|
| 30 |
+
|
| 31 |
+
kwargs (dict): Keyword argument to the body_fn.
|
| 32 |
+
|
| 33 |
+
hints (dict): A dict of context hints which could be passed to
|
| 34 |
+
backend compiler.
|
| 35 |
+
"""
|
| 36 |
+
if not isinstance(args, tuple):
|
| 37 |
+
args = tuple(args)
|
| 38 |
+
|
| 39 |
+
if not all(isinstance(t, (torch.Tensor, int, float, bool)) for t in args):
|
| 40 |
+
raise RuntimeError(
|
| 41 |
+
f"args must be a tuple of tensors, ints, floats, or bools, got {args}"
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
if not isinstance(kwargs, dict):
|
| 45 |
+
raise RuntimeError(f"kwargs must be a dict, got {type(kwargs)}")
|
| 46 |
+
|
| 47 |
+
if len(kwargs) > 0:
|
| 48 |
+
raise RuntimeError(
|
| 49 |
+
f"kwargs except for hints are not supported, got {kwargs}"
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
if not isinstance(hints, dict):
|
| 53 |
+
raise RuntimeError(f"hints must be a dict, got {type(hints)}")
|
| 54 |
+
|
| 55 |
+
for k, v in hints.items():
|
| 56 |
+
if not isinstance(k, str):
|
| 57 |
+
raise RuntimeError(f"hints key must be a str, got {k}.")
|
| 58 |
+
|
| 59 |
+
if not isinstance(v, (int, float, bool, str)):
|
| 60 |
+
raise RuntimeError(
|
| 61 |
+
"hints must be a dict containing int, float, bool or str "
|
| 62 |
+
f"value, got value {v} for key {k}."
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
# pyrefly: ignore [missing-attribute]
|
| 66 |
+
return super().__call__(body_fn, args, kwargs, hints)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
hints_wrapper = HintsWrapper()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@hints_wrapper.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 73 |
+
def hints_wrapper_dense(body_fn, args, kwargs, hints):
|
| 74 |
+
return body_fn(*args, **kwargs)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
hints_wrapper.py_autograd_impl(
|
| 78 |
+
autograd_not_implemented(hints_wrapper, deferred_error=True)
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@hints_wrapper.py_impl(FakeTensorMode)
|
| 83 |
+
def hints_wrapper_fake_tensor_mode(mode, body_func, args, kwargs, hints):
|
| 84 |
+
flat_args = pytree.tree_leaves(args)
|
| 85 |
+
with mode:
|
| 86 |
+
return body_func(*flat_args, **kwargs)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@hints_wrapper.py_functionalize_impl
|
| 90 |
+
def hints_wrapper_functionalize(ctx, body_fn, args, kwargs, hints):
|
| 91 |
+
from torch._higher_order_ops.utils import _check_alias_and_mutation
|
| 92 |
+
|
| 93 |
+
unwrapped_args = ctx.unwrap_tensors(args)
|
| 94 |
+
unwrapped_kwargs = ctx.unwrap_tensors(kwargs)
|
| 95 |
+
unwrapped_hints = ctx.unwrap_tensors(hints)
|
| 96 |
+
with ctx.redispatch_to_next():
|
| 97 |
+
functional_body_fn = ctx.functionalize(body_fn)
|
| 98 |
+
pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
|
| 99 |
+
_check_alias_and_mutation(
|
| 100 |
+
body_fn, unwrapped_args, "hints_wrapper", pre_dispatch
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
outputs = hints_wrapper(
|
| 104 |
+
functional_body_fn,
|
| 105 |
+
unwrapped_args,
|
| 106 |
+
unwrapped_kwargs,
|
| 107 |
+
unwrapped_hints,
|
| 108 |
+
)
|
| 109 |
+
return ctx.wrap_tensors(outputs)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def trace_hints_wrapper(proxy_mode, hints_wrapper, body_fn, args, kwargs, hints):
|
| 113 |
+
flat_args = tuple(pytree.tree_leaves(args))
|
| 114 |
+
body_graph = reenter_make_fx(body_fn)(*flat_args, **kwargs)
|
| 115 |
+
|
| 116 |
+
_, body_graph_name = unique_graph_id(proxy_mode, prefix="hints_wrapper_body_graph")
|
| 117 |
+
proxy_mode.tracer.root.register_module(body_graph_name, body_graph)
|
| 118 |
+
|
| 119 |
+
new_args: tuple = (body_graph, flat_args, {})
|
| 120 |
+
# merge hints into kwargs
|
| 121 |
+
new_kwargs = {}
|
| 122 |
+
new_kwargs["hints"] = hints
|
| 123 |
+
|
| 124 |
+
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, new_args)
|
| 125 |
+
proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, new_kwargs)
|
| 126 |
+
|
| 127 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 128 |
+
"call_function", hints_wrapper, proxy_args, proxy_kwargs, name="hints_wrapper"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
out = body_fn(*flat_args, **kwargs)
|
| 132 |
+
return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@hints_wrapper.py_impl(ProxyTorchDispatchMode)
|
| 136 |
+
def inner(proxy_mode, body_fn, args, kwargs, hints):
|
| 137 |
+
if proxy_mode.enable_tracing:
|
| 138 |
+
return trace_hints_wrapper(
|
| 139 |
+
proxy_mode, hints_wrapper, body_fn, args, kwargs, hints
|
| 140 |
+
)
|
| 141 |
+
else:
|
| 142 |
+
return hints_wrapper(body_fn, args, kwargs, hints)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/inline_asm_elementwise.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.utils._pytree as pytree
|
| 7 |
+
from torch._C import DispatchKey
|
| 8 |
+
from torch._higher_order_ops.utils import autograd_not_implemented
|
| 9 |
+
from torch._ops import HigherOrderOperator
|
| 10 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 11 |
+
from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ["inline_asm_elementwise"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class InlineAsmElementwiseOp(HigherOrderOperator):
|
| 18 |
+
"""Execute inline PTX assembly elementwise over tensors.
|
| 19 |
+
|
| 20 |
+
This is an elementwise map where the function body is inline assembly.
|
| 21 |
+
Input tensors are implicitly broadcast to the same shape.
|
| 22 |
+
|
| 23 |
+
Each invocation of the inline asm processes ``pack`` elements at a time.
|
| 24 |
+
Exactly which set of inputs a given invocation receives is unspecified.
|
| 25 |
+
|
| 26 |
+
Output strides follow PyTorch's standard pointwise striding propagation
|
| 27 |
+
rules.
|
| 28 |
+
|
| 29 |
+
In eager mode, the assembly is executed via the CUDA Jiterator. Under
|
| 30 |
+
``torch.compile`` the assembly is lowered to Triton's
|
| 31 |
+
``tl.inline_asm_elementwise`` via Inductor, which allows fusion with
|
| 32 |
+
surrounding operators.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
*inputs: Input tensors whose values are passed to the asm block.
|
| 36 |
+
asm_str: PTX assembly string. Operands use ``$N`` syntax
|
| 37 |
+
(e.g. ``$0`` for the first output, ``$1`` for the first input).
|
| 38 |
+
constraints: Inline-asm constraints in LLVM format. Output constraints
|
| 39 |
+
are prefixed with ``=`` (e.g. ``"=f,f,f"`` for one float output
|
| 40 |
+
and two float inputs).
|
| 41 |
+
dtype: Element type of the returned tensor.
|
| 42 |
+
is_pure: Must be ``True``. If true, the compiler may assume the asm
|
| 43 |
+
block has no side-effects.
|
| 44 |
+
pack: Number of elements processed per asm invocation. When
|
| 45 |
+
``pack > 1``, the constraint string must list ``pack`` outputs
|
| 46 |
+
and ``pack`` copies of each input. Requires ``torch.compile``.
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
A tensor with the broadcast shape of the inputs and the given dtype.
|
| 50 |
+
|
| 51 |
+
Example::
|
| 52 |
+
|
| 53 |
+
>>> # xdoctest: +SKIP(requires CUDA)
|
| 54 |
+
>>> # Float32 fused multiply-add via PTX
|
| 55 |
+
>>> result = inline_asm_elementwise(
|
| 56 |
+
... a, b, c,
|
| 57 |
+
... asm_str="fma.rn.f32 $0, $1, $2, $3;",
|
| 58 |
+
... constraints="=f,f,f,f",
|
| 59 |
+
... dtype=torch.float32,
|
| 60 |
+
... )
|
| 61 |
+
|
| 62 |
+
>>> # xdoctest: +SKIP(requires CUDA)
|
| 63 |
+
>>> # pack=2: each asm invocation processes two elements
|
| 64 |
+
>>> result = inline_asm_elementwise(
|
| 65 |
+
... x,
|
| 66 |
+
... asm_str="mov.b32 $0, $2; mov.b32 $1, $3;",
|
| 67 |
+
... constraints="=r,=r,r,r",
|
| 68 |
+
... dtype=torch.float32,
|
| 69 |
+
... pack=2,
|
| 70 |
+
... )
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(self):
|
| 74 |
+
super().__init__("inline_asm_elementwise")
|
| 75 |
+
|
| 76 |
+
def __call__(
|
| 77 |
+
self,
|
| 78 |
+
*inputs: torch.Tensor,
|
| 79 |
+
asm_str: str,
|
| 80 |
+
constraints: str,
|
| 81 |
+
dtype: torch.dtype,
|
| 82 |
+
is_pure: bool = True,
|
| 83 |
+
pack: int = 1,
|
| 84 |
+
) -> torch.Tensor:
|
| 85 |
+
if not is_pure:
|
| 86 |
+
raise ValueError("inline_asm_elementwise only supports is_pure=True")
|
| 87 |
+
# pyrefly: ignore [missing-attribute]
|
| 88 |
+
return super().__call__(
|
| 89 |
+
*inputs,
|
| 90 |
+
asm_str=asm_str,
|
| 91 |
+
constraints=constraints,
|
| 92 |
+
dtype=dtype,
|
| 93 |
+
is_pure=True,
|
| 94 |
+
pack=pack,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
inline_asm_elementwise = InlineAsmElementwiseOp()
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _parse_constraints(constraints: str) -> tuple[int, int]:
|
| 102 |
+
parts = [p.strip() for p in constraints.split(",")]
|
| 103 |
+
n_outputs = sum(1 for p in parts if p.startswith("="))
|
| 104 |
+
n_inputs = len(parts) - n_outputs
|
| 105 |
+
return n_outputs, n_inputs
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
_DTYPE_TO_CUDA_TYPE = {
|
| 109 |
+
torch.float32: "float",
|
| 110 |
+
torch.float64: "double",
|
| 111 |
+
torch.float16: "__half",
|
| 112 |
+
torch.bfloat16: "__nv_bfloat16",
|
| 113 |
+
torch.int32: "int",
|
| 114 |
+
torch.int64: "long long",
|
| 115 |
+
torch.int16: "short",
|
| 116 |
+
torch.int8: "signed char",
|
| 117 |
+
torch.uint8: "unsigned char",
|
| 118 |
+
torch.uint16: "unsigned short",
|
| 119 |
+
torch.uint32: "unsigned int",
|
| 120 |
+
torch.bool: "bool",
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
_TRITON_ARG_RE = re.compile(r"\$(\d+)")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _triton_asm_to_cuda_asm(asm_str: str) -> str:
|
| 128 |
+
return _TRITON_ARG_RE.sub(r"%\1", asm_str)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@functools.lru_cache
|
| 132 |
+
def _get_jiterator_fn(
|
| 133 |
+
asm_str: str,
|
| 134 |
+
constraints: str,
|
| 135 |
+
n_inputs: int,
|
| 136 |
+
input_dtype: torch.dtype,
|
| 137 |
+
output_dtype: torch.dtype,
|
| 138 |
+
):
|
| 139 |
+
from torch.cuda.jiterator import _create_jit_fn
|
| 140 |
+
|
| 141 |
+
cuda_asm = _triton_asm_to_cuda_asm(asm_str)
|
| 142 |
+
|
| 143 |
+
constraint_parts = [p.strip() for p in constraints.split(",")]
|
| 144 |
+
output_constraints = [p.lstrip("=") for p in constraint_parts if p.startswith("=")]
|
| 145 |
+
input_constraints = [p for p in constraint_parts if not p.startswith("=")]
|
| 146 |
+
|
| 147 |
+
if input_dtype not in _DTYPE_TO_CUDA_TYPE:
|
| 148 |
+
raise ValueError(f"Unsupported input dtype for inline asm: {input_dtype}")
|
| 149 |
+
if output_dtype not in _DTYPE_TO_CUDA_TYPE:
|
| 150 |
+
raise ValueError(f"Unsupported output dtype for inline asm: {output_dtype}")
|
| 151 |
+
|
| 152 |
+
input_type = _DTYPE_TO_CUDA_TYPE[input_dtype]
|
| 153 |
+
output_type = _DTYPE_TO_CUDA_TYPE[output_dtype]
|
| 154 |
+
|
| 155 |
+
input_params = ", ".join(f"{input_type} in{i}" for i in range(n_inputs))
|
| 156 |
+
out_constraints_str = ", ".join(f'"={c}"(result)' for c in output_constraints)
|
| 157 |
+
in_constraints_str = ", ".join(
|
| 158 |
+
f'"{c}"(in{i})' for i, c in enumerate(input_constraints)
|
| 159 |
+
)
|
| 160 |
+
escaped_asm = (
|
| 161 |
+
cuda_asm.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
code = f"""
|
| 165 |
+
template <typename T>
|
| 166 |
+
{output_type} inline_asm_kernel({input_params}) {{
|
| 167 |
+
{output_type} result;
|
| 168 |
+
asm volatile (
|
| 169 |
+
"{escaped_asm}"
|
| 170 |
+
: {out_constraints_str}
|
| 171 |
+
: {in_constraints_str}
|
| 172 |
+
);
|
| 173 |
+
return result;
|
| 174 |
+
}}
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
return _create_jit_fn(code)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _inline_asm_dense(*inputs, asm_str, constraints, dtype, is_pure, pack):
|
| 181 |
+
if not inputs:
|
| 182 |
+
raise ValueError("inline_asm_elementwise requires at least one input tensor")
|
| 183 |
+
|
| 184 |
+
inputs = torch.broadcast_tensors(*inputs)
|
| 185 |
+
|
| 186 |
+
if not inputs[0].is_cuda:
|
| 187 |
+
raise RuntimeError("inline_asm_elementwise only supports CUDA tensors")
|
| 188 |
+
|
| 189 |
+
if pack > 1:
|
| 190 |
+
raise RuntimeError(
|
| 191 |
+
"inline_asm_elementwise with pack > 1 requires torch.compile"
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
n_outputs, n_inputs = _parse_constraints(constraints)
|
| 195 |
+
|
| 196 |
+
if n_outputs != 1:
|
| 197 |
+
raise ValueError(f"Expected 1 output constraint, got {n_outputs}")
|
| 198 |
+
|
| 199 |
+
if n_inputs != len(inputs):
|
| 200 |
+
raise ValueError(
|
| 201 |
+
f"Constraint string specifies {n_inputs} inputs but got "
|
| 202 |
+
f"{len(inputs)} tensor(s)"
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
# Jiterator generates a single input type for all inputs — mixed dtypes
|
| 206 |
+
# would produce incorrect CUDA code.
|
| 207 |
+
input_dtypes = {inp.dtype for inp in inputs}
|
| 208 |
+
if len(input_dtypes) > 1:
|
| 209 |
+
raise ValueError(
|
| 210 |
+
f"All inputs must have the same dtype for eager execution, "
|
| 211 |
+
f"got {sorted(str(d) for d in input_dtypes)}"
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
jit_fn = _get_jiterator_fn(
|
| 215 |
+
asm_str=asm_str,
|
| 216 |
+
constraints=constraints,
|
| 217 |
+
n_inputs=len(inputs),
|
| 218 |
+
input_dtype=inputs[0].dtype,
|
| 219 |
+
output_dtype=dtype,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
return jit_fn(*inputs)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@inline_asm_elementwise.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 226 |
+
def _(*inputs, asm_str, constraints, dtype, is_pure=True, pack=1):
|
| 227 |
+
return _inline_asm_dense(
|
| 228 |
+
*inputs,
|
| 229 |
+
asm_str=asm_str,
|
| 230 |
+
constraints=constraints,
|
| 231 |
+
dtype=dtype,
|
| 232 |
+
is_pure=is_pure,
|
| 233 |
+
pack=pack,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
inline_asm_elementwise.py_autograd_impl(
|
| 238 |
+
autograd_not_implemented(inline_asm_elementwise, deferred_error=True)
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def _elementwise_output_like(*inputs, dtype):
|
| 243 |
+
from torch._prims_common import compute_elementwise_output_logical_to_physical_perm
|
| 244 |
+
|
| 245 |
+
broadcasted = torch.broadcast_tensors(*inputs)
|
| 246 |
+
l2p_perm, _ = compute_elementwise_output_logical_to_physical_perm(*broadcasted)
|
| 247 |
+
return torch.empty_permuted(
|
| 248 |
+
broadcasted[0].shape, l2p_perm, dtype=dtype, device=broadcasted[0].device
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@inline_asm_elementwise.py_impl(FakeTensorMode)
|
| 253 |
+
def _(mode, *inputs, asm_str, constraints, dtype, is_pure=True, pack=1):
|
| 254 |
+
with mode:
|
| 255 |
+
return _elementwise_output_like(*inputs, dtype=dtype)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@inline_asm_elementwise.py_impl(ProxyTorchDispatchMode)
|
| 259 |
+
def _(mode, *inputs, asm_str, constraints, dtype, is_pure=True, pack=1):
|
| 260 |
+
proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, inputs)
|
| 261 |
+
|
| 262 |
+
out_proxy = mode.tracer.create_proxy(
|
| 263 |
+
"call_function",
|
| 264 |
+
inline_asm_elementwise,
|
| 265 |
+
proxy_args,
|
| 266 |
+
{
|
| 267 |
+
"asm_str": asm_str,
|
| 268 |
+
"constraints": constraints,
|
| 269 |
+
"dtype": dtype,
|
| 270 |
+
"is_pure": is_pure,
|
| 271 |
+
"pack": pack,
|
| 272 |
+
},
|
| 273 |
+
name="inline_asm_elementwise",
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
out = inline_asm_elementwise(
|
| 277 |
+
*inputs,
|
| 278 |
+
asm_str=asm_str,
|
| 279 |
+
constraints=constraints,
|
| 280 |
+
dtype=dtype,
|
| 281 |
+
is_pure=is_pure,
|
| 282 |
+
pack=pack,
|
| 283 |
+
)
|
| 284 |
+
return track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@inline_asm_elementwise.py_functionalize_impl
|
| 288 |
+
def _(ctx, *inputs, asm_str, constraints, dtype, is_pure=True, pack=1):
|
| 289 |
+
unwrapped_inputs = ctx.unwrap_tensors(inputs)
|
| 290 |
+
|
| 291 |
+
with ctx.redispatch_to_next():
|
| 292 |
+
res = inline_asm_elementwise(
|
| 293 |
+
*unwrapped_inputs,
|
| 294 |
+
asm_str=asm_str,
|
| 295 |
+
constraints=constraints,
|
| 296 |
+
dtype=dtype,
|
| 297 |
+
pack=pack,
|
| 298 |
+
)
|
| 299 |
+
return ctx.wrap_tensors(res)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/invoke_leaf_function.py
ADDED
|
@@ -0,0 +1,897 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextlib
|
| 2 |
+
import functools
|
| 3 |
+
from collections.abc import Callable, Generator, Sequence
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Any, NamedTuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.utils._pytree as pytree
|
| 9 |
+
from torch._C import DispatchKey, DispatchKeySet
|
| 10 |
+
from torch._higher_order_ops.utils import register_fake
|
| 11 |
+
from torch._library.opaque_object import OpaqueBase, register_opaque_type
|
| 12 |
+
from torch._ops import HigherOrderOperator
|
| 13 |
+
from torch.autograd.graph import get_gradient_edge
|
| 14 |
+
from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
|
| 15 |
+
from torch.nn.utils.stateless import _reparametrize_module
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
_leaf_function_module_retriever: Callable[[int], Any] | None = None
|
| 19 |
+
|
| 20 |
+
# Separate storage for the make_fx / _invoke_leaf_function_python path.
|
| 21 |
+
# We can't use Dynamo's register_user_object because it requires a Source
|
| 22 |
+
# (for bytecode generation) and adds entries to index_to_bytecode_constructor.
|
| 23 |
+
# In the make_fx path we have neither a Source nor bytecode generation, so we
|
| 24 |
+
# maintain our own dict keyed by negative indices to avoid collisions with
|
| 25 |
+
# Dynamo's non-negative indices.
|
| 26 |
+
_makefx_module_storage: dict[int, torch.nn.Module] = {}
|
| 27 |
+
_makefx_next_index = 0
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def store_makefx_modules(modules: list[torch.nn.Module]) -> tuple[int, ...]:
|
| 31 |
+
"""Store modules for the make_fx path and return their assigned indices.
|
| 32 |
+
|
| 33 |
+
Uses negative indices to avoid collisions with Dynamo's register_user_object
|
| 34 |
+
which uses non-negative indices.
|
| 35 |
+
"""
|
| 36 |
+
global _makefx_next_index
|
| 37 |
+
indices = []
|
| 38 |
+
for mod in modules:
|
| 39 |
+
_makefx_next_index -= 1
|
| 40 |
+
_makefx_module_storage[_makefx_next_index] = mod
|
| 41 |
+
indices.append(_makefx_next_index)
|
| 42 |
+
return tuple(indices)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def reset_makefx_module_storage() -> None:
|
| 46 |
+
global _makefx_next_index
|
| 47 |
+
_makefx_next_index = 0
|
| 48 |
+
_makefx_module_storage.clear()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class _LeafCallable(OpaqueBase):
|
| 52 |
+
def __init__(self, fn: Callable) -> None:
|
| 53 |
+
self._fn = fn
|
| 54 |
+
|
| 55 |
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
| 56 |
+
return self._fn(*args, **kwargs)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
register_opaque_type(_LeafCallable, typ="reference")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def set_leaf_function_module_retriever(retriever: Callable[[int], Any]) -> None:
|
| 63 |
+
global _leaf_function_module_retriever
|
| 64 |
+
_leaf_function_module_retriever = retriever
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class LeafModuleState(NamedTuple):
|
| 68 |
+
"""
|
| 69 |
+
In dynamo, nn.Module arguments to leaf functions are converted to this
|
| 70 |
+
pytree format (index, parameters, buffers). This structure is then
|
| 71 |
+
flattened to produce the actual inputs to invoke_leaf_function.
|
| 72 |
+
|
| 73 |
+
At runtime, the original module is reconstructed from it.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
nn_module_index: int
|
| 77 |
+
named_parameters: dict[str, torch.nn.Parameter]
|
| 78 |
+
named_buffers: dict[str, torch.Tensor]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def convert_modules_to_states(values: Any, module_to_index: dict[int, int]) -> Any:
|
| 82 |
+
"""Replace nn.Module instances in a pytree with LeafModuleState objects.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
values: A pytree of values that may contain nn.Module instances.
|
| 86 |
+
module_to_index: Mapping from id(module) to its integer index.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def module_to_state(val: Any) -> Any:
|
| 90 |
+
if isinstance(val, torch.nn.Module):
|
| 91 |
+
return LeafModuleState(
|
| 92 |
+
nn_module_index=module_to_index[id(val)],
|
| 93 |
+
named_parameters=dict(val.named_parameters()),
|
| 94 |
+
named_buffers=dict(val.named_buffers()),
|
| 95 |
+
)
|
| 96 |
+
return val
|
| 97 |
+
|
| 98 |
+
return pytree.tree_map(module_to_state, values)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _resolve_mutated_flat_indices(
|
| 102 |
+
fn: Callable,
|
| 103 |
+
mutates_args: frozenset[str],
|
| 104 |
+
num_flat_args: int,
|
| 105 |
+
input_spec: pytree.TreeSpec,
|
| 106 |
+
) -> str:
|
| 107 |
+
"""Resolve mutates_args expressions to a comma-separated string of flat-arg indices.
|
| 108 |
+
|
| 109 |
+
Each expression in mutates_args (e.g. "x", "model.running_mean") is evaluated
|
| 110 |
+
against sentinel values to determine which flat-arg positions are mutated.
|
| 111 |
+
|
| 112 |
+
Example: for ``def fn(x, model)`` where model is an nn.Module with parameters
|
| 113 |
+
``weight`` and ``bias``, the flat args are ``[x, nn_module_index, weight, bias]``.
|
| 114 |
+
Given ``mutates_args={"model.weight"}``, this assigns sentinels ``[0, 1, 2, 3]``
|
| 115 |
+
to the flat args, evaluates ``model.weight`` to ``2``, and returns ``"2"``.
|
| 116 |
+
"""
|
| 117 |
+
import inspect
|
| 118 |
+
|
| 119 |
+
class _AttrDict:
|
| 120 |
+
pass
|
| 121 |
+
|
| 122 |
+
def _set_nested_attr(obj: _AttrDict, fqn: str, value: Any) -> None:
|
| 123 |
+
parts = fqn.split(".")
|
| 124 |
+
for part in parts[:-1]:
|
| 125 |
+
if not hasattr(obj, part):
|
| 126 |
+
setattr(obj, part, _AttrDict())
|
| 127 |
+
obj = getattr(obj, part)
|
| 128 |
+
setattr(obj, parts[-1], value)
|
| 129 |
+
|
| 130 |
+
def _lms_to_attr_dict(val: Any) -> Any:
|
| 131 |
+
if isinstance(val, LeafModuleState):
|
| 132 |
+
target = _AttrDict()
|
| 133 |
+
for fqn, sentinel in val.named_parameters.items():
|
| 134 |
+
_set_nested_attr(target, fqn, sentinel)
|
| 135 |
+
for fqn, sentinel in val.named_buffers.items():
|
| 136 |
+
_set_nested_attr(target, fqn, sentinel)
|
| 137 |
+
return target
|
| 138 |
+
return val
|
| 139 |
+
|
| 140 |
+
sig = inspect.signature(fn)
|
| 141 |
+
sentinels = list(range(num_flat_args))
|
| 142 |
+
args_struct, kwargs_struct = pytree.tree_unflatten(sentinels, input_spec)
|
| 143 |
+
args_eval, kwargs_eval = pytree.tree_map(
|
| 144 |
+
_lms_to_attr_dict,
|
| 145 |
+
(args_struct, kwargs_struct),
|
| 146 |
+
is_leaf=lambda x: isinstance(x, LeafModuleState),
|
| 147 |
+
)
|
| 148 |
+
namespace = dict(sig.bind(*args_eval, **kwargs_eval).arguments)
|
| 149 |
+
|
| 150 |
+
indices: list[int] = []
|
| 151 |
+
for expr in mutates_args:
|
| 152 |
+
# Empty __builtins__ prevents access to builtins like __import__, open, exec.
|
| 153 |
+
result = eval(expr, {"__builtins__": {}}, namespace) # noqa: S307
|
| 154 |
+
leaves = pytree.tree_leaves(result)
|
| 155 |
+
for sentinel in leaves:
|
| 156 |
+
if not isinstance(sentinel, int):
|
| 157 |
+
raise ValueError(
|
| 158 |
+
f"mutates_args expression '{expr}' resolved to a non-leaf value "
|
| 159 |
+
f"of type {type(sentinel).__name__}. Expressions must resolve to "
|
| 160 |
+
f"individual tensor positions, e.g. 'model.weight' not 'model'."
|
| 161 |
+
)
|
| 162 |
+
indices.append(sentinel)
|
| 163 |
+
indices.sort()
|
| 164 |
+
return ",".join(str(i) for i in indices)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@dataclass
|
| 168 |
+
class GradientInfo:
|
| 169 |
+
"""
|
| 170 |
+
We need the gradient edge to trigger the autograd engine backward.
|
| 171 |
+
|
| 172 |
+
We need the tensor metadata (size, stride, dtype, device) to create zeros when
|
| 173 |
+
gradient is None at runtime but required by the backward graph (because the graph
|
| 174 |
+
is traced with fake implementation).
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
edge: torch.autograd.graph.GradientEdge
|
| 178 |
+
size: torch.Size
|
| 179 |
+
stride: tuple[int, ...]
|
| 180 |
+
dtype: torch.dtype
|
| 181 |
+
device: torch.device
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _retrieve_module_by_index(nn_module_index: int) -> torch.nn.Module:
|
| 185 |
+
# Check make_fx storage first (used by _invoke_leaf_function_python).
|
| 186 |
+
# Fall back to the Dynamo retriever (used by the compiled path).
|
| 187 |
+
if nn_module_index in _makefx_module_storage:
|
| 188 |
+
if nn_module_index >= 0:
|
| 189 |
+
raise RuntimeError(
|
| 190 |
+
f"Expected negative nn_module_index for non-strict trace over leaf_function, but got {nn_module_index}."
|
| 191 |
+
)
|
| 192 |
+
return _makefx_module_storage[nn_module_index]
|
| 193 |
+
|
| 194 |
+
if _leaf_function_module_retriever is None:
|
| 195 |
+
raise RuntimeError("Leaf function module retriever not set.")
|
| 196 |
+
|
| 197 |
+
mod = _leaf_function_module_retriever(nn_module_index)
|
| 198 |
+
if not isinstance(mod, torch.nn.Module):
|
| 199 |
+
raise TypeError(
|
| 200 |
+
f"Expected nn.Module at index {nn_module_index} for leaf function invocation, "
|
| 201 |
+
f"but got {type(mod).__name__}."
|
| 202 |
+
)
|
| 203 |
+
return mod
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def check_escaped_gradients(
|
| 207 |
+
outputs: Any,
|
| 208 |
+
inputs: Sequence[Any],
|
| 209 |
+
requires_grad_indices: set[int],
|
| 210 |
+
) -> None:
|
| 211 |
+
"""
|
| 212 |
+
Check if autograd graph depends on tensors that not passed as explicit inputs.
|
| 213 |
+
|
| 214 |
+
Controlled by torch._dynamo.config.leaf_function_check_escaped_gradients.
|
| 215 |
+
"""
|
| 216 |
+
if not requires_grad_indices:
|
| 217 |
+
return
|
| 218 |
+
|
| 219 |
+
import torch._dynamo.config as config
|
| 220 |
+
|
| 221 |
+
if not config.leaf_function_check_escaped_gradients:
|
| 222 |
+
return
|
| 223 |
+
|
| 224 |
+
input_nodes: set[torch.autograd.graph.Node] = set()
|
| 225 |
+
for i, inp in enumerate(inputs):
|
| 226 |
+
if (
|
| 227 |
+
isinstance(inp, torch.Tensor)
|
| 228 |
+
and i in requires_grad_indices
|
| 229 |
+
and inp.requires_grad
|
| 230 |
+
):
|
| 231 |
+
edge = get_gradient_edge(inp)
|
| 232 |
+
if edge.node is not None:
|
| 233 |
+
input_nodes.add(edge.node)
|
| 234 |
+
|
| 235 |
+
flat_outputs = outputs if isinstance(outputs, tuple) else (outputs,)
|
| 236 |
+
start_nodes: set[torch.autograd.graph.Node] = {
|
| 237 |
+
out.grad_fn
|
| 238 |
+
for out in flat_outputs
|
| 239 |
+
if isinstance(out, torch.Tensor)
|
| 240 |
+
and out.requires_grad
|
| 241 |
+
and out.grad_fn is not None
|
| 242 |
+
}
|
| 243 |
+
if not start_nodes:
|
| 244 |
+
return
|
| 245 |
+
|
| 246 |
+
escaped: set[torch.autograd.graph.Node] = set()
|
| 247 |
+
visited: set[torch.autograd.graph.Node] = set()
|
| 248 |
+
stack = list(start_nodes)
|
| 249 |
+
|
| 250 |
+
while stack:
|
| 251 |
+
node = stack.pop()
|
| 252 |
+
if node in visited or node in input_nodes:
|
| 253 |
+
continue
|
| 254 |
+
visited.add(node)
|
| 255 |
+
|
| 256 |
+
for next_node, _ in node.next_functions:
|
| 257 |
+
if next_node is None or next_node in input_nodes:
|
| 258 |
+
continue
|
| 259 |
+
if not next_node.next_functions:
|
| 260 |
+
escaped.add(next_node)
|
| 261 |
+
else:
|
| 262 |
+
stack.append(next_node)
|
| 263 |
+
|
| 264 |
+
if escaped:
|
| 265 |
+
tensor_info = []
|
| 266 |
+
for node in escaped:
|
| 267 |
+
if hasattr(node, "variable"):
|
| 268 |
+
t = node.variable
|
| 269 |
+
tensor_info.append(
|
| 270 |
+
f" - Tensor(shape={list(t.shape)}, dtype={t.dtype})"
|
| 271 |
+
)
|
| 272 |
+
tensor_details = (
|
| 273 |
+
"\n".join(tensor_info) if tensor_info else " (tensor details unavailable)"
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
raise RuntimeError(
|
| 277 |
+
f"@leaf_function detected {len(escaped)} tensor(s) with requires_grad=True "
|
| 278 |
+
f"that are not passed as explicit inputs:\n{tensor_details}\n"
|
| 279 |
+
f"Gradients will not flow back to closure-captured or global tensors. "
|
| 280 |
+
f"Pass them as explicit arguments to the leaf function."
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
@contextlib.contextmanager
|
| 285 |
+
def unflatten_args_with_modules(
|
| 286 |
+
flat_args: tuple[Any, ...], input_spec: pytree.TreeSpec
|
| 287 |
+
) -> Generator[tuple[list[Any] | tuple[Any, ...], dict[str, Any]], None, None]:
|
| 288 |
+
args, kwargs = pytree.tree_unflatten(flat_args, input_spec)
|
| 289 |
+
|
| 290 |
+
with contextlib.ExitStack() as stack:
|
| 291 |
+
|
| 292 |
+
def process_module_state(state: LeafModuleState) -> torch.nn.Module:
|
| 293 |
+
orig_module = _retrieve_module_by_index(state.nn_module_index)
|
| 294 |
+
stack.enter_context(
|
| 295 |
+
_reparametrize_module(
|
| 296 |
+
orig_module,
|
| 297 |
+
{**state.named_parameters, **state.named_buffers},
|
| 298 |
+
)
|
| 299 |
+
)
|
| 300 |
+
return orig_module
|
| 301 |
+
|
| 302 |
+
new_args, new_kwargs = pytree.tree_map_only(
|
| 303 |
+
LeafModuleState,
|
| 304 |
+
process_module_state,
|
| 305 |
+
(args, kwargs),
|
| 306 |
+
is_leaf=lambda x: isinstance(x, LeafModuleState),
|
| 307 |
+
)
|
| 308 |
+
yield new_args, new_kwargs
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def flatten_args_with_modules(
|
| 312 |
+
args_kwargs: tuple[Any, ...],
|
| 313 |
+
) -> list[Any]:
|
| 314 |
+
def expand_module(x: Any) -> Any:
|
| 315 |
+
if isinstance(x, torch.nn.Module):
|
| 316 |
+
return LeafModuleState(
|
| 317 |
+
nn_module_index=-1,
|
| 318 |
+
named_parameters=dict(x.named_parameters()),
|
| 319 |
+
named_buffers=dict(x.named_buffers()),
|
| 320 |
+
)
|
| 321 |
+
return x
|
| 322 |
+
|
| 323 |
+
expanded = pytree.tree_map(expand_module, args_kwargs)
|
| 324 |
+
return pytree.tree_leaves(expanded)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def make_leaf_function_wrappers(
|
| 328 |
+
real_fn: Callable[..., Any],
|
| 329 |
+
fake_fn: Callable[..., Any],
|
| 330 |
+
captured_out_spec: list[pytree.TreeSpec | None],
|
| 331 |
+
) -> tuple[Callable[..., tuple[Any, ...]], Callable[..., tuple[Any, ...]]]:
|
| 332 |
+
"""Wrap real_fn and fake_fn to flatten outputs and capture the output TreeSpec.
|
| 333 |
+
|
| 334 |
+
Both wrappers share the same captured output spec: the first call (typically
|
| 335 |
+
fake_fn during tracing) records it, and subsequent calls verify consistency.
|
| 336 |
+
The caller passes in a single-element list and reads captured_out_spec[0]
|
| 337 |
+
after the wrappers have been called.
|
| 338 |
+
|
| 339 |
+
Used by both the Dynamo path (_call_leaf_function in torch.py) and the
|
| 340 |
+
make_fx path (_invoke_leaf_function_python in decorators.py).
|
| 341 |
+
"""
|
| 342 |
+
|
| 343 |
+
def _wrap(fn: Callable[..., Any]) -> Callable[..., tuple[Any, ...]]:
|
| 344 |
+
if len(captured_out_spec) != 1:
|
| 345 |
+
raise RuntimeError(
|
| 346 |
+
f"captured_out_spec must be a single-element list, got length {len(captured_out_spec)}"
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
def wrapper(*args: Any, **kwargs: Any) -> tuple[Any, ...]:
|
| 350 |
+
out = fn(*args, **kwargs)
|
| 351 |
+
|
| 352 |
+
flat_out, out_spec = pytree.tree_flatten(out)
|
| 353 |
+
if captured_out_spec[0] is None:
|
| 354 |
+
captured_out_spec[0] = out_spec
|
| 355 |
+
elif captured_out_spec[0] != out_spec:
|
| 356 |
+
raise AssertionError(
|
| 357 |
+
f"leaf_function output structure mismatch: "
|
| 358 |
+
f"expected {captured_out_spec[0]}, got {out_spec}. "
|
| 359 |
+
f"This can happen if the real function and fake function return "
|
| 360 |
+
f"different pytree structures (e.g., dict vs tuple, different number "
|
| 361 |
+
f"of elements). Ensure both functions return the same structure."
|
| 362 |
+
)
|
| 363 |
+
return tuple(flat_out)
|
| 364 |
+
|
| 365 |
+
return wrapper
|
| 366 |
+
|
| 367 |
+
return _wrap(real_fn), _wrap(fake_fn)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def autograd_grad_with_gradient_info(
|
| 371 |
+
output_infos: Sequence[GradientInfo | None],
|
| 372 |
+
input_infos: Sequence[GradientInfo | None],
|
| 373 |
+
grad_outputs: Sequence[Any] | None = None,
|
| 374 |
+
retain_graph: bool | None = None,
|
| 375 |
+
create_graph: bool = False,
|
| 376 |
+
allow_unused: bool = False,
|
| 377 |
+
) -> tuple[torch.Tensor | None, ...]:
|
| 378 |
+
"""
|
| 379 |
+
Compute gradients using GradientInfo, it additionally handles the case
|
| 380 |
+
where input and output infos are None.
|
| 381 |
+
|
| 382 |
+
Args:
|
| 383 |
+
output_infos: GradientInfo for each output (None if no grad_fn),
|
| 384 |
+
input_infos: GradientInfo for each input (None if not requires_grad)
|
| 385 |
+
grad_outputs: Gradients w.r.t. outputs
|
| 386 |
+
|
| 387 |
+
Returns a tuple of gradients with None for inputs that don't require grad.
|
| 388 |
+
"""
|
| 389 |
+
filtered_output_edges = []
|
| 390 |
+
filtered_grad_outputs = []
|
| 391 |
+
for i, info in enumerate(output_infos):
|
| 392 |
+
if info is not None and info.edge.node is not None:
|
| 393 |
+
filtered_output_edges.append(info.edge)
|
| 394 |
+
if grad_outputs is not None:
|
| 395 |
+
filtered_grad_outputs.append(grad_outputs[i])
|
| 396 |
+
|
| 397 |
+
filtered_input_edges = []
|
| 398 |
+
filtered_input_infos = []
|
| 399 |
+
input_indices = []
|
| 400 |
+
for i, info in enumerate(input_infos):
|
| 401 |
+
if info is not None:
|
| 402 |
+
filtered_input_edges.append(info.edge)
|
| 403 |
+
filtered_input_infos.append(info)
|
| 404 |
+
input_indices.append(i)
|
| 405 |
+
|
| 406 |
+
if not filtered_output_edges or not filtered_input_edges:
|
| 407 |
+
return tuple(None for _ in input_infos)
|
| 408 |
+
|
| 409 |
+
grads = torch.autograd.grad(
|
| 410 |
+
outputs=filtered_output_edges,
|
| 411 |
+
inputs=filtered_input_edges,
|
| 412 |
+
grad_outputs=filtered_grad_outputs if grad_outputs is not None else None,
|
| 413 |
+
retain_graph=retain_graph,
|
| 414 |
+
create_graph=create_graph,
|
| 415 |
+
allow_unused=allow_unused,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
# Reconstruct full gradient tuple with Nones at proper positions.
|
| 419 |
+
#
|
| 420 |
+
# NB: For unused inputs that require grad, we return zeros instead of None.
|
| 421 |
+
# This is necessary because during AOT tracing, we use fake_impl to determine
|
| 422 |
+
# the backward graph structure. fake_impl may not accurately reflect which
|
| 423 |
+
# inputs are truly used for gradients in real_impl. For example, users often
|
| 424 |
+
# write fake_impl by returning torch.empty_like(input) to get the right shape
|
| 425 |
+
# without actually using the input in a differentiable computation. So we must
|
| 426 |
+
# be permissive and assume all inputs with requires_grad=True could need
|
| 427 |
+
# gradients. When multiple invoke_leaf_function calls share an input (e.g.,
|
| 428 |
+
# a module's forward + hook both receiving the same tensor), the traced
|
| 429 |
+
# backward graph generates explicit add operations to accumulate their
|
| 430 |
+
# gradients. At runtime, if one leaf function doesn't actually use the input,
|
| 431 |
+
# autograd.grad returns None for it, and the traced add(grad1, grad2) fails
|
| 432 |
+
# because one operand is None. Returning zeros ensures the add always works.
|
| 433 |
+
result: list[torch.Tensor | None] = [None] * len(input_infos)
|
| 434 |
+
for filtered_idx, original_idx in enumerate(input_indices):
|
| 435 |
+
grad = grads[filtered_idx]
|
| 436 |
+
if grad is None:
|
| 437 |
+
info = filtered_input_infos[filtered_idx]
|
| 438 |
+
grad = torch.empty_strided(
|
| 439 |
+
info.size, info.stride, dtype=info.dtype, device=info.device
|
| 440 |
+
).zero_()
|
| 441 |
+
result[original_idx] = grad
|
| 442 |
+
|
| 443 |
+
return tuple(result)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def _make_forward(
|
| 447 |
+
fn: Callable,
|
| 448 |
+
include_keys: DispatchKeySet,
|
| 449 |
+
exclude_keys: DispatchKeySet,
|
| 450 |
+
) -> tuple[Callable, dict[str, Any]]:
|
| 451 |
+
state: dict[str, Any] = {"inputs": None, "outputs": None}
|
| 452 |
+
|
| 453 |
+
@functools.wraps(fn)
|
| 454 |
+
def forward(*args, **kwargs):
|
| 455 |
+
effective_keys = include_keys
|
| 456 |
+
if include_keys.has(DispatchKey.PythonDispatcher):
|
| 457 |
+
effective_keys = effective_keys.remove(DispatchKey.PythonDispatcher)
|
| 458 |
+
if effective_keys.has(DispatchKey.Python):
|
| 459 |
+
effective_keys = effective_keys.remove(DispatchKey.Python)
|
| 460 |
+
with torch._C._ForceDispatchKeyGuard(effective_keys, exclude_keys):
|
| 461 |
+
with torch.enable_grad():
|
| 462 |
+
outputs = fn(*args, **kwargs)
|
| 463 |
+
|
| 464 |
+
flat_inputs = flatten_args_with_modules((args, kwargs))
|
| 465 |
+
requires_grad_indices = {
|
| 466 |
+
i
|
| 467 |
+
for i, inp in enumerate(flat_inputs)
|
| 468 |
+
if isinstance(inp, torch.Tensor) and inp.requires_grad
|
| 469 |
+
}
|
| 470 |
+
check_escaped_gradients(outputs, flat_inputs, requires_grad_indices)
|
| 471 |
+
|
| 472 |
+
state["inputs"] = tuple(
|
| 473 |
+
GradientInfo(
|
| 474 |
+
edge=get_gradient_edge(inp),
|
| 475 |
+
size=inp.size(),
|
| 476 |
+
stride=inp.stride(),
|
| 477 |
+
dtype=inp.dtype,
|
| 478 |
+
device=inp.device,
|
| 479 |
+
)
|
| 480 |
+
if isinstance(inp, torch.Tensor) and inp.requires_grad
|
| 481 |
+
else None
|
| 482 |
+
for inp in flat_inputs
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
if outputs is None:
|
| 486 |
+
state["outputs"] = ()
|
| 487 |
+
else:
|
| 488 |
+
state["outputs"] = tuple(
|
| 489 |
+
GradientInfo(
|
| 490 |
+
edge=get_gradient_edge(out),
|
| 491 |
+
size=out.size(),
|
| 492 |
+
stride=out.stride(),
|
| 493 |
+
dtype=out.dtype,
|
| 494 |
+
device=out.device,
|
| 495 |
+
)
|
| 496 |
+
if isinstance(out, torch.Tensor)
|
| 497 |
+
and out.requires_grad
|
| 498 |
+
and out.grad_fn is not None
|
| 499 |
+
else None
|
| 500 |
+
for out in outputs
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
return pytree.tree_map_only(
|
| 504 |
+
torch.Tensor,
|
| 505 |
+
lambda t: t.detach().requires_grad_(t.requires_grad),
|
| 506 |
+
outputs,
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
return forward, state
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
class InvokeLeafFunction(HigherOrderOperator):
|
| 513 |
+
def __init__(self):
|
| 514 |
+
super().__init__("invoke_leaf_function", supports_training_input_mutation=True)
|
| 515 |
+
|
| 516 |
+
def __call__(
|
| 517 |
+
self,
|
| 518 |
+
real_fn_callable,
|
| 519 |
+
fake_fn_callable,
|
| 520 |
+
input_spec,
|
| 521 |
+
mutated_arg_indices,
|
| 522 |
+
*flat_args,
|
| 523 |
+
requires_grad_indices="",
|
| 524 |
+
):
|
| 525 |
+
"""
|
| 526 |
+
real_fn_callable: _LeafCallable wrapping the real function
|
| 527 |
+
fake_fn_callable: _LeafCallable wrapping the fake function
|
| 528 |
+
input_spec: pytree.TreeSpec for unflattening flat_args back to (args, kwargs)
|
| 529 |
+
mutated_arg_indices: comma-separated string of flat-arg indices that are
|
| 530 |
+
declared as mutated (e.g. "1,2"), or "" for no mutations. Encoded as a
|
| 531 |
+
string so it is a pytree leaf for the HOP schema infrastructure.
|
| 532 |
+
requires_grad_indices: comma-separated string of flat-arg indices that
|
| 533 |
+
require grad (e.g. "0,1"), or "" for none.
|
| 534 |
+
"""
|
| 535 |
+
return super().__call__( # type: ignore[attr-defined]
|
| 536 |
+
real_fn_callable,
|
| 537 |
+
fake_fn_callable,
|
| 538 |
+
input_spec,
|
| 539 |
+
mutated_arg_indices,
|
| 540 |
+
*flat_args,
|
| 541 |
+
requires_grad_indices=requires_grad_indices,
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
# pyrefly: ignore [bad-override]
|
| 545 |
+
def gen_schema(
|
| 546 |
+
self,
|
| 547 |
+
real_fn_callable,
|
| 548 |
+
fake_fn_callable,
|
| 549 |
+
input_spec,
|
| 550 |
+
mutated_arg_indices,
|
| 551 |
+
*flat_args,
|
| 552 |
+
requires_grad_indices="",
|
| 553 |
+
):
|
| 554 |
+
from torch._higher_order_ops.schema import HopSchemaGenerator
|
| 555 |
+
from torch._higher_order_ops.utils import _maybe_fake_prop_ignore_unbacked
|
| 556 |
+
from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing
|
| 557 |
+
|
| 558 |
+
mutated_set = _parse_mutated_arg_indices(mutated_arg_indices)
|
| 559 |
+
|
| 560 |
+
with disable_proxy_modes_tracing():
|
| 561 |
+
if mutated_set:
|
| 562 |
+
schema_flat_args = tuple(
|
| 563 |
+
arg.detach().clone()
|
| 564 |
+
if isinstance(arg, torch.Tensor) and i in mutated_set
|
| 565 |
+
else arg
|
| 566 |
+
for i, arg in enumerate(flat_args)
|
| 567 |
+
)
|
| 568 |
+
else:
|
| 569 |
+
schema_flat_args = flat_args
|
| 570 |
+
|
| 571 |
+
def run_fake(*unfunc_flat_args):
|
| 572 |
+
with unflatten_args_with_modules(unfunc_flat_args, input_spec) as (
|
| 573 |
+
args,
|
| 574 |
+
kwargs,
|
| 575 |
+
):
|
| 576 |
+
return fake_fn_callable(*args, **kwargs)
|
| 577 |
+
|
| 578 |
+
fake_outputs = _maybe_fake_prop_ignore_unbacked(run_fake, schema_flat_args)
|
| 579 |
+
|
| 580 |
+
gen = HopSchemaGenerator(self)
|
| 581 |
+
gen.add_arg("real_fn_callable", real_fn_callable)
|
| 582 |
+
gen.add_arg("fake_fn_callable", fake_fn_callable)
|
| 583 |
+
gen.add_arg("input_spec", input_spec)
|
| 584 |
+
gen.add_arg("mutated_arg_indices", mutated_arg_indices)
|
| 585 |
+
for i, arg in enumerate(flat_args):
|
| 586 |
+
gen.add_arg(f"arg{i}", arg, is_mutated=i in mutated_set)
|
| 587 |
+
gen.add_arg(
|
| 588 |
+
"requires_grad_indices",
|
| 589 |
+
requires_grad_indices,
|
| 590 |
+
default_value="",
|
| 591 |
+
kw_only=True,
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
if isinstance(fake_outputs, tuple):
|
| 595 |
+
for out in fake_outputs:
|
| 596 |
+
gen.add_output(out)
|
| 597 |
+
else:
|
| 598 |
+
if fake_outputs is not None:
|
| 599 |
+
raise AssertionError(
|
| 600 |
+
f"Expected fake_outputs to be a tuple or None, got {type(fake_outputs)}"
|
| 601 |
+
)
|
| 602 |
+
gen.add_output(fake_outputs)
|
| 603 |
+
|
| 604 |
+
return gen.gen_schema()
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
invoke_leaf_function = InvokeLeafFunction()
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
# NOTE: [Autograd support for invoke_leaf_function]
|
| 611 |
+
#
|
| 612 |
+
# The overall idea is that when the real forward executes, we are going to build an autograd graph
|
| 613 |
+
# and save it. When the real backward executes, we are going to invoke the autograd graph.
|
| 614 |
+
# We need to build these "real_forward" and "real_backward" functions from the "real_fn".
|
| 615 |
+
#
|
| 616 |
+
# Inputs:
|
| 617 |
+
# real_fn_callable/fake_fn_callable are _LeafCallable objects that wrap real_fn and fake_fn.
|
| 618 |
+
# These functions were created in dynamo by wrapping the user's original leaf function and fake function:
|
| 619 |
+
# - They accept *flat_args (flattened LeafModuleState objects + other args)
|
| 620 |
+
# - They unflatten flat_args and convert LeafModuleState back to nn.Modules
|
| 621 |
+
# - They call the user's original leaf function with the reconstructed args
|
| 622 |
+
# - They return the user function's outputs
|
| 623 |
+
#
|
| 624 |
+
# We wrap real_fn (via _make_forward) to handle autograd properly:
|
| 625 |
+
# 1. Detach inputs and outputs to isolate the leaf function's autograd graph from the
|
| 626 |
+
# outer graph (gradients flow through our backward, not internal ops)
|
| 627 |
+
# 2. Real function is invoked at backend dispatch keys (i.e. CompositeExplicitAutograd)
|
| 628 |
+
# where autograd is disabled. We re-enable grad and restore dispatch keys for the autograd engine to work.
|
| 629 |
+
# 3. Store GradientInfo (gradient edges + tensor metadata) instead of full tensors for backward,
|
| 630 |
+
# which is sufficient for autograd.grad and avoids keeping tensors alive.
|
| 631 |
+
#
|
| 632 |
+
# We automatically generate backward functions:
|
| 633 |
+
# - real_backward uses the stored input/output GradientInfo and invokes the autograd engine
|
| 634 |
+
# - fake_backward creates empty gradients for inputs that requires grad
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
class InvokeLeafFunctionAutogradOp(torch.autograd.Function):
|
| 638 |
+
@staticmethod
|
| 639 |
+
# pyrefly: ignore [bad-override]
|
| 640 |
+
def forward(
|
| 641 |
+
ctx,
|
| 642 |
+
real_fn_callable,
|
| 643 |
+
fake_fn_callable,
|
| 644 |
+
input_spec,
|
| 645 |
+
mutated_arg_indices,
|
| 646 |
+
*flat_args,
|
| 647 |
+
):
|
| 648 |
+
include_keys = torch._C._dispatch_tls_local_include_set()
|
| 649 |
+
exclude_keys = torch._C._dispatch_tls_local_exclude_set()
|
| 650 |
+
|
| 651 |
+
requires_grad_indices = ",".join(
|
| 652 |
+
str(i)
|
| 653 |
+
for i, arg in enumerate(flat_args)
|
| 654 |
+
if isinstance(arg, torch.Tensor) and arg.requires_grad
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
real_forward, real_state = _make_forward(
|
| 658 |
+
real_fn_callable, include_keys, exclude_keys
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
def real_backward(*grads):
|
| 662 |
+
if real_state["inputs"] is None or real_state["outputs"] is None:
|
| 663 |
+
raise RuntimeError(
|
| 664 |
+
"invoke_leaf_function backward expects inputs/outputs to be set in forward."
|
| 665 |
+
)
|
| 666 |
+
return autograd_grad_with_gradient_info(
|
| 667 |
+
output_infos=real_state["outputs"],
|
| 668 |
+
input_infos=real_state["inputs"],
|
| 669 |
+
grad_outputs=grads,
|
| 670 |
+
allow_unused=True,
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
input_infos_for_fake = tuple(
|
| 674 |
+
GradientInfo(
|
| 675 |
+
edge=None, # type: ignore[arg-type]
|
| 676 |
+
size=arg.size(),
|
| 677 |
+
stride=arg.stride(),
|
| 678 |
+
dtype=arg.dtype,
|
| 679 |
+
device=arg.device,
|
| 680 |
+
)
|
| 681 |
+
if isinstance(arg, torch.Tensor) and arg.requires_grad
|
| 682 |
+
else None
|
| 683 |
+
for arg in flat_args
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
def fake_backward(*grads):
|
| 687 |
+
return tuple(
|
| 688 |
+
torch.empty_strided(
|
| 689 |
+
info.size, info.stride, dtype=info.dtype, device=info.device
|
| 690 |
+
)
|
| 691 |
+
if info is not None
|
| 692 |
+
else None
|
| 693 |
+
for info in input_infos_for_fake
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
new_real_fn_callable = _LeafCallable(real_forward)
|
| 697 |
+
|
| 698 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 699 |
+
fw_outputs = invoke_leaf_function(
|
| 700 |
+
new_real_fn_callable,
|
| 701 |
+
fake_fn_callable,
|
| 702 |
+
input_spec,
|
| 703 |
+
mutated_arg_indices,
|
| 704 |
+
*flat_args,
|
| 705 |
+
requires_grad_indices=requires_grad_indices,
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
ctx.real_backward = real_backward
|
| 709 |
+
ctx.fake_backward = fake_backward
|
| 710 |
+
|
| 711 |
+
return fw_outputs
|
| 712 |
+
|
| 713 |
+
@staticmethod
|
| 714 |
+
# pyrefly: ignore [bad-override]
|
| 715 |
+
def backward(ctx, *grads):
|
| 716 |
+
real_bw_callable = _LeafCallable(ctx.real_backward)
|
| 717 |
+
fake_bw_callable = _LeafCallable(ctx.fake_backward)
|
| 718 |
+
_, bw_input_spec = pytree.tree_flatten((grads, {}))
|
| 719 |
+
fw_grads = invoke_leaf_function(
|
| 720 |
+
real_bw_callable, fake_bw_callable, bw_input_spec, "", *grads
|
| 721 |
+
)
|
| 722 |
+
return None, None, None, None, *fw_grads
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
@invoke_leaf_function.py_autograd_impl
|
| 726 |
+
def invoke_leaf_function_autograd(
|
| 727 |
+
real_fn_callable,
|
| 728 |
+
fake_fn_callable,
|
| 729 |
+
input_spec,
|
| 730 |
+
mutated_arg_indices,
|
| 731 |
+
*flat_args,
|
| 732 |
+
requires_grad_indices="",
|
| 733 |
+
):
|
| 734 |
+
return InvokeLeafFunctionAutogradOp.apply(
|
| 735 |
+
real_fn_callable, fake_fn_callable, input_spec, mutated_arg_indices, *flat_args
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
# TODO: aliasing is not allowed
|
| 740 |
+
@invoke_leaf_function.py_functionalize_impl
|
| 741 |
+
def invoke_leaf_function_functionalization(ctx, *all_args, **kwargs):
|
| 742 |
+
from torch._higher_order_ops.auto_functionalize import (
|
| 743 |
+
can_auto_functionalize,
|
| 744 |
+
do_auto_functionalize_v2,
|
| 745 |
+
)
|
| 746 |
+
from torch._higher_order_ops.utils import HopInstance
|
| 747 |
+
|
| 748 |
+
unwrapped_args = ctx.unwrap_tensors(all_args)
|
| 749 |
+
hop_instance = HopInstance.create(invoke_leaf_function, *unwrapped_args, **kwargs)
|
| 750 |
+
if can_auto_functionalize(hop_instance):
|
| 751 |
+
return do_auto_functionalize_v2(ctx.mode, hop_instance, all_args, kwargs)
|
| 752 |
+
|
| 753 |
+
from torch._higher_order_ops.effects import handle_effects
|
| 754 |
+
|
| 755 |
+
return handle_effects(
|
| 756 |
+
ctx.mode._allow_token_discovery,
|
| 757 |
+
ctx.mode._tokens,
|
| 758 |
+
invoke_leaf_function,
|
| 759 |
+
all_args,
|
| 760 |
+
kwargs,
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
@invoke_leaf_function.py_impl(ProxyTorchDispatchMode)
|
| 765 |
+
def invoke_leaf_function_proxy_mode(proxy_mode, *all_args, **kwargs):
|
| 766 |
+
out = invoke_leaf_function(*all_args, **kwargs)
|
| 767 |
+
proxies = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, all_args)
|
| 768 |
+
proxy = proxy_mode.tracer.create_proxy(
|
| 769 |
+
"call_function", invoke_leaf_function, proxies, kwargs
|
| 770 |
+
)
|
| 771 |
+
return track_tensor_tree(out, proxy, constant=None, tracer=proxy_mode.tracer)
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
def _validate_outputs_match(
|
| 775 |
+
fake_output: Any,
|
| 776 |
+
real_output: Any,
|
| 777 |
+
) -> None:
|
| 778 |
+
"""
|
| 779 |
+
Validate that fake_fn and real_fn outputs have matching pytree structure,
|
| 780 |
+
shapes, and dtypes.
|
| 781 |
+
|
| 782 |
+
Raises:
|
| 783 |
+
RuntimeError: If outputs don't match with detailed error message.
|
| 784 |
+
"""
|
| 785 |
+
fake_flat, fake_spec = pytree.tree_flatten(fake_output)
|
| 786 |
+
real_flat, real_spec = pytree.tree_flatten(real_output)
|
| 787 |
+
|
| 788 |
+
if fake_spec != real_spec:
|
| 789 |
+
raise RuntimeError(
|
| 790 |
+
f"Output structure mismatch in @leaf_function decorator.\n"
|
| 791 |
+
f"fake_impl returned structure: {fake_spec}\n"
|
| 792 |
+
f"real_impl returned structure: {real_spec}\n"
|
| 793 |
+
f"The fake_impl must return outputs with the same pytree structure as real_impl."
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
if len(fake_flat) != len(real_flat):
|
| 797 |
+
raise RuntimeError(
|
| 798 |
+
f"Output count mismatch in @leaf_function decorator.\n"
|
| 799 |
+
f"fake_impl returned {len(fake_flat)} values\n"
|
| 800 |
+
f"real_impl returned {len(real_flat)} values"
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
for i, (fake_val, real_val) in enumerate(zip(fake_flat, real_flat)):
|
| 804 |
+
fake_is_tensor = isinstance(fake_val, torch.Tensor)
|
| 805 |
+
real_is_tensor = isinstance(real_val, torch.Tensor)
|
| 806 |
+
|
| 807 |
+
if fake_is_tensor != real_is_tensor:
|
| 808 |
+
raise RuntimeError(
|
| 809 |
+
f"Output type mismatch at position {i} in @leaf_function decorator.\n"
|
| 810 |
+
f"fake_impl returned: {type(fake_val).__name__}\n"
|
| 811 |
+
f"real_impl returned: {type(real_val).__name__}"
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
if fake_is_tensor:
|
| 815 |
+
if fake_val.shape != real_val.shape:
|
| 816 |
+
raise RuntimeError(
|
| 817 |
+
f"Shape mismatch at output position {i} in @leaf_function decorator.\n"
|
| 818 |
+
f"fake_impl output shape: {list(fake_val.shape)}\n"
|
| 819 |
+
f"real_impl output shape: {list(real_val.shape)}\n"
|
| 820 |
+
f"The fake_impl must produce tensors with the same shapes as real_impl."
|
| 821 |
+
)
|
| 822 |
+
|
| 823 |
+
if fake_val.dtype != real_val.dtype:
|
| 824 |
+
raise RuntimeError(
|
| 825 |
+
f"Dtype mismatch at output position {i} in @leaf_function decorator.\n"
|
| 826 |
+
f"fake_impl output dtype: {fake_val.dtype}\n"
|
| 827 |
+
f"real_impl output dtype: {real_val.dtype}\n"
|
| 828 |
+
f"The fake_impl must produce tensors with the same dtypes as real_impl."
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
def _parse_mutated_arg_indices(s: str) -> set[int]:
|
| 833 |
+
return {int(x) for x in s.split(",") if x}
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
def _check_no_input_mutation(
|
| 837 |
+
flat_args: tuple[Any, ...],
|
| 838 |
+
version_before: list[int],
|
| 839 |
+
mutated_arg_indices: str = "",
|
| 840 |
+
) -> None:
|
| 841 |
+
mutated_set = _parse_mutated_arg_indices(mutated_arg_indices)
|
| 842 |
+
for i, arg in enumerate(flat_args):
|
| 843 |
+
if isinstance(arg, torch.Tensor) and arg._version != version_before[i]:
|
| 844 |
+
if i not in mutated_set:
|
| 845 |
+
raise RuntimeError(
|
| 846 |
+
f"Undeclared in-place mutation on input tensor at position {i}. "
|
| 847 |
+
f"Declare it in @leaf_function(mutates_args=...) or avoid mutating inputs."
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
@register_fake(invoke_leaf_function)
|
| 852 |
+
def invoke_leaf_function_fake(
|
| 853 |
+
real_fn_callable,
|
| 854 |
+
fake_fn_callable,
|
| 855 |
+
input_spec,
|
| 856 |
+
mutated_arg_indices,
|
| 857 |
+
*flat_args,
|
| 858 |
+
requires_grad_indices="",
|
| 859 |
+
):
|
| 860 |
+
with unflatten_args_with_modules(flat_args, input_spec) as (args, kwargs):
|
| 861 |
+
return fake_fn_callable(*args, **kwargs)
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
@invoke_leaf_function.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 865 |
+
def invoke_leaf_function_dense(
|
| 866 |
+
real_fn_callable,
|
| 867 |
+
fake_fn_callable,
|
| 868 |
+
input_spec,
|
| 869 |
+
mutated_arg_indices,
|
| 870 |
+
*flat_args,
|
| 871 |
+
requires_grad_indices="",
|
| 872 |
+
):
|
| 873 |
+
from torch._dynamo import config as dynamo_config
|
| 874 |
+
|
| 875 |
+
version_before = [
|
| 876 |
+
arg._version if isinstance(arg, torch.Tensor) else 0 for arg in flat_args
|
| 877 |
+
]
|
| 878 |
+
|
| 879 |
+
flat_args = tuple(
|
| 880 |
+
arg.detach() if isinstance(arg, torch.Tensor) else arg for arg in flat_args
|
| 881 |
+
)
|
| 882 |
+
requires_grad_indices_set = _parse_mutated_arg_indices(requires_grad_indices)
|
| 883 |
+
flat_args = tuple(
|
| 884 |
+
arg.requires_grad_(True) if idx in requires_grad_indices_set else arg
|
| 885 |
+
for idx, arg in enumerate(flat_args)
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
with unflatten_args_with_modules(flat_args, input_spec) as (args, kwargs):
|
| 889 |
+
real_output = real_fn_callable(*args, **kwargs)
|
| 890 |
+
|
| 891 |
+
_check_no_input_mutation(flat_args, version_before, mutated_arg_indices)
|
| 892 |
+
|
| 893 |
+
if dynamo_config.leaf_function_validate_outputs:
|
| 894 |
+
fake_output = fake_fn_callable(*args, **kwargs)
|
| 895 |
+
_validate_outputs_match(fake_output, real_output)
|
| 896 |
+
|
| 897 |
+
return real_output
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/invoke_subgraph.py
ADDED
|
@@ -0,0 +1,1070 @@
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import copy
|
| 5 |
+
import functools
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from collections.abc import Callable
|
| 8 |
+
from contextlib import nullcontext
|
| 9 |
+
from dataclasses import dataclass, field
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.utils._pytree as pytree
|
| 14 |
+
from torch._C import DispatchKey
|
| 15 |
+
from torch._dispatch.python import suspend_functionalization
|
| 16 |
+
from torch._higher_order_ops.utils import (
|
| 17 |
+
_from_fun,
|
| 18 |
+
_maybe_reenter_make_fx,
|
| 19 |
+
clone_outputs_aliasing_inputs,
|
| 20 |
+
FunctionalizeCtxWrapper,
|
| 21 |
+
get_dummy_aot_autograd_config,
|
| 22 |
+
HopInstance,
|
| 23 |
+
prepare_fw_with_masks,
|
| 24 |
+
redirect_to_mode,
|
| 25 |
+
reenter_make_fx,
|
| 26 |
+
register_fake,
|
| 27 |
+
save_values_for_backward,
|
| 28 |
+
saved_values,
|
| 29 |
+
)
|
| 30 |
+
from torch._library.fake_class_registry import FakeScriptObject
|
| 31 |
+
from torch._library.opaque_object import is_opaque_type
|
| 32 |
+
from torch._ops import HigherOrderOperator
|
| 33 |
+
from torch._subclasses.functional_tensor import disable_functional_mode
|
| 34 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 35 |
+
disable_proxy_modes_tracing,
|
| 36 |
+
ProxyTorchDispatchMode,
|
| 37 |
+
track_tensor_tree,
|
| 38 |
+
)
|
| 39 |
+
from torch.fx.graph_module import GraphModule
|
| 40 |
+
from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts
|
| 41 |
+
from torch.utils._debug_mode import DebugMode
|
| 42 |
+
from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
invoke_subgraph_counter = 0
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# During the tracing of the joint graph, we construct this information. This is
|
| 49 |
+
# used to filter out grad_outs/tangents in the `backward` method of
|
| 50 |
+
# InvokeSubgraphAutogradOp.
|
| 51 |
+
@dataclass
|
| 52 |
+
class OutputMetadata:
|
| 53 |
+
num_fw_outs: int | None = None
|
| 54 |
+
indexes_with_symint: set[int] = field(default_factory=set)
|
| 55 |
+
indexes_with_no_grad: set[int] = field(default_factory=set)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# This config will be stored in invoke_subgraph HOP node.meta["custom"]["nested_region_config"]
|
| 59 |
+
# as well as the subgraph's gm.meta["nested_region_config"].
|
| 60 |
+
@dataclass
|
| 61 |
+
class NestedCompileRegionOptions:
|
| 62 |
+
# A Callable that takes (gm, example_inputs, decompositions=None, **kwargs) as inputs.
|
| 63 |
+
# Returns AOTCompiledArtifact
|
| 64 |
+
fw_compiler: Callable | None = None
|
| 65 |
+
bw_compiler: Callable | None = None
|
| 66 |
+
|
| 67 |
+
# Note: [InvokeSubgraphHOP Partitioner]
|
| 68 |
+
# If not None, add "partitioner" to HOP node meta.
|
| 69 |
+
# If Callable, directly assign the callable, but the callable cannot be pickled
|
| 70 |
+
# If str, the options are "default_partition" and "min_cut_rematerialization_partition".
|
| 71 |
+
# The HOP joint graph will be partitioned using the corresponding functions in
|
| 72 |
+
# torch/_functorch/partitioners.py
|
| 73 |
+
partitioner: Callable | str | None = None
|
| 74 |
+
|
| 75 |
+
# If it's None, we'll inherit the parent call's decompositions.
|
| 76 |
+
# Otherwise, the nested region will use this decompositions.
|
| 77 |
+
decompositions: dict[str, Any] | None = None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _extract_nested_region_config(fn):
|
| 81 |
+
"""
|
| 82 |
+
Extract the NestedCompileRegionOptions from the HOP subgraph gm.meta["nested_region_config"]
|
| 83 |
+
"""
|
| 84 |
+
gm_to_compile = None
|
| 85 |
+
if isinstance(fn, torch.fx.GraphModule):
|
| 86 |
+
gm_to_compile = fn
|
| 87 |
+
elif isinstance(fn, FunctionalizeCtxWrapper):
|
| 88 |
+
gm_to_compile = fn.subgraph
|
| 89 |
+
|
| 90 |
+
if (
|
| 91 |
+
isinstance(gm_to_compile, torch.fx.GraphModule)
|
| 92 |
+
and hasattr(gm_to_compile, "meta")
|
| 93 |
+
and "nested_region_config" in gm_to_compile.meta
|
| 94 |
+
):
|
| 95 |
+
if isinstance(
|
| 96 |
+
gm_to_compile.meta["nested_region_config"], NestedCompileRegionOptions
|
| 97 |
+
):
|
| 98 |
+
return gm_to_compile.meta["nested_region_config"].decompositions
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class InvokeSubgraphHOP(HigherOrderOperator):
|
| 103 |
+
def __init__(self) -> None:
|
| 104 |
+
# Invoke subgraph does not have any state, it is just a wrapper over a
|
| 105 |
+
# subgraph, so we can safely cache the HOP.
|
| 106 |
+
super().__init__("invoke_subgraph", cacheable=True)
|
| 107 |
+
# This is used by the fake tensor cache key validator to extract the
|
| 108 |
+
# subgraph and iterate over the nodes to find if all nodes are fake
|
| 109 |
+
# tensor cacheable.
|
| 110 |
+
self.subgraph_indexes = [
|
| 111 |
+
0,
|
| 112 |
+
]
|
| 113 |
+
|
| 114 |
+
# identifier is setup by upper part of the stack. This helps us in
|
| 115 |
+
# identifying two invoke_subgraph calls have same subgraph.
|
| 116 |
+
def __call__(
|
| 117 |
+
self,
|
| 118 |
+
subgraph: GraphModule | FunctionalizeCtxWrapper,
|
| 119 |
+
identifier: str | None,
|
| 120 |
+
*operands,
|
| 121 |
+
):
|
| 122 |
+
if identifier is not None and not isinstance(identifier, str):
|
| 123 |
+
raise AssertionError(
|
| 124 |
+
f"identifier must be None or a string, got {type(identifier)}"
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if not all(
|
| 128 |
+
isinstance(
|
| 129 |
+
o, (torch.Tensor, int, torch.SymInt, torch.Generator, FakeScriptObject)
|
| 130 |
+
)
|
| 131 |
+
or is_opaque_type(type(o))
|
| 132 |
+
for o in operands
|
| 133 |
+
if o is not None
|
| 134 |
+
):
|
| 135 |
+
raise AssertionError(
|
| 136 |
+
f"invoke_subgraph operands must be a list of tensors/ints/SymInts/Generator, got {operands}"
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
# pyrefly: ignore [missing-attribute]
|
| 140 |
+
return super().__call__(subgraph, identifier, *operands)
|
| 141 |
+
|
| 142 |
+
# pyrefly: ignore [bad-override]
|
| 143 |
+
def gen_schema(self, subgraph, identifier, *operands):
|
| 144 |
+
from torch._higher_order_ops.schema import HopSchemaGenerator
|
| 145 |
+
from torch._higher_order_ops.utils import (
|
| 146 |
+
check_input_alias_and_mutation_return_outputs,
|
| 147 |
+
materialize_as_graph,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
subgraph_decomp_table = _extract_nested_region_config(subgraph)
|
| 151 |
+
gm: torch.fx.GraphModule = materialize_as_graph(
|
| 152 |
+
subgraph, operands, subgraph_decomp_table=subgraph_decomp_table
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
schema_gen = HopSchemaGenerator(self)
|
| 156 |
+
schema_gen.add_arg("subgraph", gm)
|
| 157 |
+
schema_gen.add_arg("identifier", identifier)
|
| 158 |
+
(
|
| 159 |
+
_,
|
| 160 |
+
_,
|
| 161 |
+
_,
|
| 162 |
+
mutated_inputs,
|
| 163 |
+
outputs,
|
| 164 |
+
) = check_input_alias_and_mutation_return_outputs(gm)
|
| 165 |
+
for idx, arg in enumerate(operands):
|
| 166 |
+
schema_gen.add_arg(f"arg{idx}", arg, is_mutated=idx in mutated_inputs)
|
| 167 |
+
for out in outputs:
|
| 168 |
+
schema_gen.add_output(out)
|
| 169 |
+
|
| 170 |
+
return schema_gen.gen_schema()
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
invoke_subgraph = InvokeSubgraphHOP()
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def invoke_subgraph_infer(
|
| 177 |
+
subgraph: GraphModule | FunctionalizeCtxWrapper,
|
| 178 |
+
*operands,
|
| 179 |
+
):
|
| 180 |
+
"""Inference-only entrypoint for invoke_subgraph that auto-generates identifier.
|
| 181 |
+
|
| 182 |
+
This is intended for use cases where we are building an inference graph and
|
| 183 |
+
don't need the forward/backward caching that requires a stable identifier.
|
| 184 |
+
The identifier is automatically computed based on the current proxy mode's
|
| 185 |
+
tracer state.
|
| 186 |
+
|
| 187 |
+
If no proxy mode is active, the subgraph is called directly.
|
| 188 |
+
"""
|
| 189 |
+
from torch.fx.experimental.proxy_tensor import get_proxy_mode
|
| 190 |
+
|
| 191 |
+
proxy_mode = get_proxy_mode()
|
| 192 |
+
if proxy_mode is None:
|
| 193 |
+
# No tracing active, just call the subgraph directly
|
| 194 |
+
if getattr(subgraph, "_boxed_call", False):
|
| 195 |
+
return subgraph(list(operands))
|
| 196 |
+
else:
|
| 197 |
+
return subgraph(*operands)
|
| 198 |
+
|
| 199 |
+
from torch._dynamo.utils import get_unique_name_wrt
|
| 200 |
+
|
| 201 |
+
# How exactly should we allocate names for the HOP invoke_subgraph we
|
| 202 |
+
# are going to put into the graph? This is a bit tricky. In the
|
| 203 |
+
# original design of invoke_subgraph, this HOP never shows up in the
|
| 204 |
+
# wild: it is only generated Dynamo, so Dynamo can take sure of
|
| 205 |
+
# ensuring it picks unique names in the context of the particular
|
| 206 |
+
# Dynamo compilation. However, these invoke_subgraph are different:
|
| 207 |
+
# they live as Dynamo compiled code that can potentially get traced
|
| 208 |
+
# multiple times! If they get retraced several times in the same
|
| 209 |
+
# trace, deduplication occurs; but if I make_fx a function f once,
|
| 210 |
+
# and then do a separate new trace, there's no relationship between
|
| 211 |
+
# these. Additionally, we also want the name we put in the graph to
|
| 212 |
+
# be deterministic, and for it to be indifferent to how many
|
| 213 |
+
# unrelated invoke_subgraphs/make_fxs we've done, prior to THIS
|
| 214 |
+
# particular make_fx.
|
| 215 |
+
#
|
| 216 |
+
# To satisfy all of these constraints, it's impossible to preallocate
|
| 217 |
+
# a name before tracing actually goes through us (since those names
|
| 218 |
+
# would have to all be unique even if a subgraph never gets used.)
|
| 219 |
+
# So we allocate the subgraph a fresh name PER proxy mode, and then
|
| 220 |
+
# consistently reuse it if it hits again.
|
| 221 |
+
#
|
| 222 |
+
# Note we do NOT do equality comparison subgraph, since it has
|
| 223 |
+
# reference equality semantics.
|
| 224 |
+
|
| 225 |
+
if subgraph in proxy_mode._invoke_subgraph_cache:
|
| 226 |
+
name = proxy_mode._invoke_subgraph_cache[subgraph]
|
| 227 |
+
else:
|
| 228 |
+
name = get_unique_name_wrt(
|
| 229 |
+
"invoke_subgraph",
|
| 230 |
+
proxy_mode._invoke_subgraph_names,
|
| 231 |
+
requires_suffix=True,
|
| 232 |
+
)
|
| 233 |
+
proxy_mode._invoke_subgraph_names.add(name)
|
| 234 |
+
proxy_mode._invoke_subgraph_cache[subgraph] = name
|
| 235 |
+
|
| 236 |
+
return invoke_subgraph(subgraph, name, *operands)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
# Registers dispatches for SAC
|
| 240 |
+
redirect_to_mode(invoke_subgraph, _CachingTorchDispatchMode)
|
| 241 |
+
redirect_to_mode(invoke_subgraph, _CachedTorchDispatchMode)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def invoke_subgraph_placeholder(func, *args, **kwargs):
|
| 245 |
+
if torch.compiler.is_dynamo_compiling():
|
| 246 |
+
# This is just a placeholder for Dynamo to replace with invoke_subgraph
|
| 247 |
+
raise RuntimeError("invoke_subgraph should not be called directly in Dynamo")
|
| 248 |
+
|
| 249 |
+
if torch.compiler.is_compiling():
|
| 250 |
+
# For non-strict export tracing, we still want to go through Dynamo
|
| 251 |
+
|
| 252 |
+
def _invoke_subgraph_placeholder_wrapper(func, args):
|
| 253 |
+
return invoke_subgraph_placeholder(func, *args)
|
| 254 |
+
|
| 255 |
+
from torch._higher_order_ops.utils import _hop_compile_and_call
|
| 256 |
+
|
| 257 |
+
return _hop_compile_and_call(_invoke_subgraph_placeholder_wrapper, (func, args))
|
| 258 |
+
|
| 259 |
+
return func(*args, **kwargs)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def mark_compile_region(
|
| 263 |
+
fn=None,
|
| 264 |
+
options: NestedCompileRegionOptions | None = None,
|
| 265 |
+
max_reuse_entries: int = 8,
|
| 266 |
+
reuse_hash_fn=None,
|
| 267 |
+
):
|
| 268 |
+
"""
|
| 269 |
+
This wrapper instructs torch.compile to compile the wrapped region once and
|
| 270 |
+
reuse the compiled artifact, instead of the usual way of aggressively
|
| 271 |
+
inlining the function.
|
| 272 |
+
|
| 273 |
+
Under the hood, it tells TorchDynamo to use InvokeSubgraph HOP for the
|
| 274 |
+
region. For PyTorch eager, this is a no-op.
|
| 275 |
+
|
| 276 |
+
Args:
|
| 277 |
+
fn: The function to wrap
|
| 278 |
+
options: Optional config to use for compiling the subgraph.
|
| 279 |
+
Warning: this is an experimental feature under development and
|
| 280 |
+
not ready for use yet.
|
| 281 |
+
max_reuse_entries: Maximum number of reuse cache entries per function
|
| 282 |
+
before raising an error. If this limit is hit, guards keep failing
|
| 283 |
+
across invocations and hierarchical compilation is not effective.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
def wrap(func):
|
| 287 |
+
def inner(*args, **kwargs):
|
| 288 |
+
# Get the innermost function to avoid nested compile regions
|
| 289 |
+
inner_func = func
|
| 290 |
+
while hasattr(inner_func, "__marked_compile_region_fn__"):
|
| 291 |
+
inner_func = inner_func.__marked_compile_region_fn__
|
| 292 |
+
return invoke_subgraph_placeholder(inner_func, *args, **kwargs)
|
| 293 |
+
|
| 294 |
+
inner.__marked_compile_region_fn__ = func # type: ignore[attr-defined]
|
| 295 |
+
func.__marked_compile_region_config__ = options # type: ignore[attr-defined]
|
| 296 |
+
func.__marked_compile_region_max_reuse_entries__ = max_reuse_entries # type: ignore[attr-defined]
|
| 297 |
+
func.__marked_compile_region_reuse_hash_fn__ = reuse_hash_fn # type: ignore[attr-defined]
|
| 298 |
+
|
| 299 |
+
return inner
|
| 300 |
+
|
| 301 |
+
if fn:
|
| 302 |
+
return wrap(fn)
|
| 303 |
+
else:
|
| 304 |
+
return wrap
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def get_invoke_subgraph_cache():
|
| 308 |
+
cache = None
|
| 309 |
+
if tracing_ctx := torch._guards.TracingContext.try_get():
|
| 310 |
+
cache = tracing_ctx.hop_dispatch_set_cache.get_cache(invoke_subgraph)
|
| 311 |
+
return cache
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# TODO (@anijain2305) - Delete this function when base_hop uses invoke_subgraph infra
|
| 315 |
+
def trace_joint_graph(fn, fw_inputs, fw_outputs):
|
| 316 |
+
"""
|
| 317 |
+
Naively trace out a joint graph. This simplifies the reconstruction of joint
|
| 318 |
+
graph in the min-cut partitioner later on.
|
| 319 |
+
"""
|
| 320 |
+
from torch._functorch.aot_autograd import create_joint
|
| 321 |
+
|
| 322 |
+
dummy_aot_config = get_dummy_aot_autograd_config()
|
| 323 |
+
|
| 324 |
+
# This joint_fn is inserted as the backward graph as is. This simplifies the
|
| 325 |
+
# min-cut partitioner work later on.
|
| 326 |
+
# Input signature - (*primals, *tangents)
|
| 327 |
+
# Output signature - (*grads, *fw_outs)
|
| 328 |
+
# The output signature is deliberately kept grads first and fw_outs second.
|
| 329 |
+
# Having grads first makes the min-cut partitioner HOP graph stitching
|
| 330 |
+
# easier.
|
| 331 |
+
def joint_fn(*primals_and_tangents):
|
| 332 |
+
primals = primals_and_tangents[: len(fw_inputs)]
|
| 333 |
+
tangents = primals_and_tangents[len(fw_inputs) :]
|
| 334 |
+
|
| 335 |
+
fw_outs, grads = create_joint(
|
| 336 |
+
prepare_fw_with_masks(fn), aot_config=dummy_aot_config
|
| 337 |
+
)(primals, tangents)
|
| 338 |
+
|
| 339 |
+
maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents)
|
| 340 |
+
|
| 341 |
+
# return signature is deliberately kept (*grads, *fw_outs). This
|
| 342 |
+
# simplifies partitioning work later on.
|
| 343 |
+
return pytree.tree_map(maybe_clone, tuple(grads + list(fw_outs)))
|
| 344 |
+
|
| 345 |
+
primals = list(fw_inputs)
|
| 346 |
+
# This assumes that the tangent strides match fw_outputs strides. Check the
|
| 347 |
+
# InvokeSubgraphAutogradOp backward op for the contiguous call.
|
| 348 |
+
tangents = [_from_fun(out) for out in fw_outputs]
|
| 349 |
+
|
| 350 |
+
joint_operands = primals + tangents
|
| 351 |
+
|
| 352 |
+
return _maybe_reenter_make_fx(joint_fn)(*joint_operands)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
# TODO (@anijain2305) - Delete this function when base_hop uses invoke_subgraph infra
|
| 356 |
+
def create_fw_bw_graph(subgraph, operands, grad_outputs=None):
|
| 357 |
+
with suspend_functionalization(), disable_functional_mode():
|
| 358 |
+
with disable_proxy_modes_tracing():
|
| 359 |
+
# args are functional tensors, generate some example tensors
|
| 360 |
+
fw_inputs = pytree.tree_map(_from_fun, operands)
|
| 361 |
+
|
| 362 |
+
from torch._guards import detect_fake_mode
|
| 363 |
+
|
| 364 |
+
fake_mode = detect_fake_mode(fw_inputs)
|
| 365 |
+
context = (
|
| 366 |
+
nullcontext()
|
| 367 |
+
if fake_mode is None or fake_mode.shape_env is None
|
| 368 |
+
else fake_mode.shape_env.ignore_fresh_unbacked_symbols()
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
with context:
|
| 372 |
+
fw_outs = pytree.tree_map(_from_fun, subgraph(*fw_inputs))
|
| 373 |
+
|
| 374 |
+
num_fw_outs = len(fw_outs)
|
| 375 |
+
|
| 376 |
+
# Collect the indexes of none in the output to check that the grad
|
| 377 |
+
# is None at the corresponding index in the backward. This check is
|
| 378 |
+
# performed in the autograd.Function - InvokeSubgraphAutogradOp.
|
| 379 |
+
# Also collect the indexes of no_grad in the output to filter out
|
| 380 |
+
# the grad_outs in the `backward` method.
|
| 381 |
+
output_metadata = OutputMetadata()
|
| 382 |
+
|
| 383 |
+
output_metadata.num_fw_outs = num_fw_outs
|
| 384 |
+
for idx, fw_out in enumerate(fw_outs):
|
| 385 |
+
if isinstance(fw_out, torch.SymInt):
|
| 386 |
+
output_metadata.indexes_with_symint.add(idx)
|
| 387 |
+
elif not fw_out.requires_grad:
|
| 388 |
+
output_metadata.indexes_with_no_grad.add(idx)
|
| 389 |
+
|
| 390 |
+
if grad_outputs is None:
|
| 391 |
+
# Infer grad_outputs to be the same properties as the fw_outputs
|
| 392 |
+
# if they're not passed in
|
| 393 |
+
# Although fw_outs are equivalent to grad_outputs for tracing
|
| 394 |
+
# purposes, we have to carefully handle the None and fw_out that do
|
| 395 |
+
# not have require_grad. At those indexes, we will have None in the
|
| 396 |
+
# backward graph.
|
| 397 |
+
grad_outputs = fw_outs
|
| 398 |
+
grad_outputs = [grad for grad in grad_outputs if grad is not None]
|
| 399 |
+
grad_outputs = [grad for grad in grad_outputs if grad.requires_grad]
|
| 400 |
+
|
| 401 |
+
# Force grad_out to be contiguous. This is because at runtime,
|
| 402 |
+
# grad_out could have different strides than fw_outs. So, we
|
| 403 |
+
# force the grad_outs to be contiguous for both tracing and
|
| 404 |
+
# runtime.
|
| 405 |
+
grad_outputs = [grad.contiguous() for grad in grad_outputs]
|
| 406 |
+
|
| 407 |
+
if any(
|
| 408 |
+
not isinstance(out, torch.Tensor)
|
| 409 |
+
for out in grad_outputs
|
| 410 |
+
if out is not None
|
| 411 |
+
):
|
| 412 |
+
raise RuntimeError(
|
| 413 |
+
"Expect outputs of invoke_subgraph to only contains tensors or None. "
|
| 414 |
+
f"Got types {[type(out) for out in grad_outputs]}."
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
# Trace the forward subgraph
|
| 418 |
+
fw_graph = _maybe_reenter_make_fx(subgraph)(*fw_inputs)
|
| 419 |
+
|
| 420 |
+
# Trace the joint graph and assign it to the bwd graph
|
| 421 |
+
bw_graph = trace_joint_graph(
|
| 422 |
+
subgraph,
|
| 423 |
+
fw_inputs,
|
| 424 |
+
grad_outputs,
|
| 425 |
+
)
|
| 426 |
+
return fw_graph, bw_graph, output_metadata
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def get_output_metadata(subgraph, *operands):
|
| 430 |
+
"""
|
| 431 |
+
Extract metadata about the subgraph outputs WITHOUT executing the subgraph.
|
| 432 |
+
This avoids running side-effectful operations twice (once here, once in forward).
|
| 433 |
+
We analyze the graph structure statically to extract metadata.
|
| 434 |
+
"""
|
| 435 |
+
# Unwrap FunctionalizeCtxWrapper if present
|
| 436 |
+
if isinstance(subgraph, FunctionalizeCtxWrapper):
|
| 437 |
+
subgraph = subgraph.subgraph
|
| 438 |
+
|
| 439 |
+
# If not a GraphModule, fall back to execution-based metadata extraction
|
| 440 |
+
if not isinstance(subgraph, torch.fx.GraphModule):
|
| 441 |
+
return _get_output_metadata_by_execution(subgraph, *operands)
|
| 442 |
+
|
| 443 |
+
output_metadata = OutputMetadata()
|
| 444 |
+
|
| 445 |
+
# Extract output arguments from the output node
|
| 446 |
+
# The output node has args=(output_values,) where output_values is a tuple/list
|
| 447 |
+
output_node = next(reversed(subgraph.graph.find_nodes(op="output")))
|
| 448 |
+
output_metadata.num_fw_outs = len(output_node.args[0])
|
| 449 |
+
|
| 450 |
+
for idx, output_arg in enumerate(output_node.args[0]):
|
| 451 |
+
if not isinstance(output_arg, torch.fx.Node):
|
| 452 |
+
if isinstance(output_arg, int):
|
| 453 |
+
output_metadata.indexes_with_symint.add(idx)
|
| 454 |
+
output_metadata.indexes_with_no_grad.add(idx)
|
| 455 |
+
continue
|
| 456 |
+
|
| 457 |
+
# Check node metadata for type information
|
| 458 |
+
if output_arg.meta.get("val") is None:
|
| 459 |
+
# If we don't have complete metadata for all outputs, fall back to execution
|
| 460 |
+
# This is important for correctness (e.g., detecting SymInts) even though it
|
| 461 |
+
# runs side-effectful operations
|
| 462 |
+
return _get_output_metadata_by_execution(subgraph, *operands)
|
| 463 |
+
|
| 464 |
+
val = output_arg.meta["val"]
|
| 465 |
+
if isinstance(val, torch.SymInt):
|
| 466 |
+
output_metadata.indexes_with_symint.add(idx)
|
| 467 |
+
output_metadata.indexes_with_no_grad.add(idx)
|
| 468 |
+
elif isinstance(val, torch.Tensor):
|
| 469 |
+
# Check if tensor requires grad from metadata
|
| 470 |
+
if hasattr(val, "requires_grad") and not val.requires_grad:
|
| 471 |
+
output_metadata.indexes_with_no_grad.add(idx)
|
| 472 |
+
else:
|
| 473 |
+
# Non-tensor, non-symint (shouldn't happen but be safe)
|
| 474 |
+
output_metadata.indexes_with_no_grad.add(idx)
|
| 475 |
+
|
| 476 |
+
return output_metadata
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def _get_output_metadata_by_execution(subgraph, *operands):
|
| 480 |
+
"""
|
| 481 |
+
Fallback: Extract metadata by executing the subgraph.
|
| 482 |
+
This should only be used when static analysis fails.
|
| 483 |
+
WARNING: This will run side-effectful operations!
|
| 484 |
+
"""
|
| 485 |
+
|
| 486 |
+
with suspend_functionalization(), disable_functional_mode():
|
| 487 |
+
with disable_proxy_modes_tracing():
|
| 488 |
+
# args are functional tensors, generate some example tensors
|
| 489 |
+
fw_inputs = pytree.tree_map(_from_fun, operands)
|
| 490 |
+
|
| 491 |
+
from torch._guards import detect_fake_mode
|
| 492 |
+
|
| 493 |
+
fake_mode = detect_fake_mode(fw_inputs)
|
| 494 |
+
context = (
|
| 495 |
+
nullcontext()
|
| 496 |
+
if fake_mode is None or fake_mode.shape_env is None
|
| 497 |
+
else fake_mode.shape_env.ignore_fresh_unbacked_symbols()
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
with context:
|
| 501 |
+
fw_outs = pytree.tree_map(_from_fun, subgraph(*fw_inputs))
|
| 502 |
+
|
| 503 |
+
num_fw_outs = len(fw_outs)
|
| 504 |
+
|
| 505 |
+
output_metadata = OutputMetadata()
|
| 506 |
+
output_metadata.num_fw_outs = num_fw_outs
|
| 507 |
+
|
| 508 |
+
for idx, fw_out in enumerate(fw_outs):
|
| 509 |
+
if isinstance(fw_out, torch.SymInt):
|
| 510 |
+
output_metadata.indexes_with_symint.add(idx)
|
| 511 |
+
elif not fw_out.requires_grad:
|
| 512 |
+
output_metadata.indexes_with_no_grad.add(idx)
|
| 513 |
+
|
| 514 |
+
return output_metadata
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def trace_joint_graph_as_bwd(
|
| 518 |
+
subgraph, num_primals, joint_operands, include_key_set, exclude_key_set
|
| 519 |
+
):
|
| 520 |
+
"""
|
| 521 |
+
Naively trace out a joint graph. This simplifies the reconstruction of joint
|
| 522 |
+
graph in the min-cut partitioner later on.
|
| 523 |
+
"""
|
| 524 |
+
from torch._functorch.aot_autograd import create_joint
|
| 525 |
+
|
| 526 |
+
dummy_aot_config = get_dummy_aot_autograd_config()
|
| 527 |
+
|
| 528 |
+
if isinstance(subgraph, torch.fx.GraphModule):
|
| 529 |
+
|
| 530 |
+
def graph_with_interpreter(*args):
|
| 531 |
+
# Running graph with interpreter is needed for propagating the stack_trace
|
| 532 |
+
with torch.fx.traceback.preserve_node_meta():
|
| 533 |
+
return torch.fx.Interpreter(subgraph).run(*args)
|
| 534 |
+
|
| 535 |
+
fn = graph_with_interpreter
|
| 536 |
+
else:
|
| 537 |
+
fn = subgraph
|
| 538 |
+
|
| 539 |
+
# This joint_fn is inserted as the backward graph as is. This simplifies the
|
| 540 |
+
# min-cut partitioner work later on.
|
| 541 |
+
# Input signature - (*primals, *tangents)
|
| 542 |
+
# Output signature - (*grads, *fw_outs)
|
| 543 |
+
# The output signature is deliberately kept grads first and fw_outs second.
|
| 544 |
+
# Having grads first makes the min-cut partitioner HOP graph stitching
|
| 545 |
+
# easier.
|
| 546 |
+
def joint_fn(*primals_and_tangents):
|
| 547 |
+
primals = primals_and_tangents[:num_primals]
|
| 548 |
+
tangents = primals_and_tangents[num_primals:]
|
| 549 |
+
|
| 550 |
+
fw_outs, grads = create_joint(
|
| 551 |
+
prepare_fw_with_masks(fn), aot_config=dummy_aot_config
|
| 552 |
+
)(primals, tangents)
|
| 553 |
+
|
| 554 |
+
maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents)
|
| 555 |
+
|
| 556 |
+
# return signature is deliberately kept (*grads, *fw_outs). This
|
| 557 |
+
# simplifies partitioning work later on.
|
| 558 |
+
return pytree.tree_map(maybe_clone, tuple(grads + list(fw_outs)))
|
| 559 |
+
|
| 560 |
+
with suspend_functionalization(), disable_functional_mode():
|
| 561 |
+
with disable_proxy_modes_tracing():
|
| 562 |
+
joint_operands = [_from_fun(arg) for arg in joint_operands]
|
| 563 |
+
with contextlib.ExitStack() as stack:
|
| 564 |
+
stack.enter_context(
|
| 565 |
+
torch._C._ForceDispatchKeyGuard(include_key_set, exclude_key_set),
|
| 566 |
+
)
|
| 567 |
+
subgraph_decomp_table = _extract_nested_region_config(subgraph)
|
| 568 |
+
with torch.enable_grad():
|
| 569 |
+
return _maybe_reenter_make_fx(
|
| 570 |
+
joint_fn, subgraph_decomp_table=subgraph_decomp_table
|
| 571 |
+
)(*joint_operands)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
class InvokeSubgraphAutogradOp(torch.autograd.Function):
|
| 575 |
+
"""
|
| 576 |
+
Saves the subgraph, i.e. original callable, in the forward method. And then
|
| 577 |
+
traces out a joint graph in the backward. This delaying of tracing in
|
| 578 |
+
backward, also called as lazy backward, ensures that the assumptions about
|
| 579 |
+
the grad_out strides and tensor-subclass-ness are already accounted for.
|
| 580 |
+
"""
|
| 581 |
+
|
| 582 |
+
@staticmethod
|
| 583 |
+
# pyrefly: ignore [bad-override]
|
| 584 |
+
def forward(
|
| 585 |
+
ctx,
|
| 586 |
+
subgraph,
|
| 587 |
+
identifier,
|
| 588 |
+
output_metadata,
|
| 589 |
+
*operands,
|
| 590 |
+
):
|
| 591 |
+
# We want to delay the backward graph construction until the backward.
|
| 592 |
+
# So in forward, we just run the fw callable as is. And save all the
|
| 593 |
+
# information necessary to construct the backward graph in the ctx.
|
| 594 |
+
ctx._subgraph = subgraph
|
| 595 |
+
ctx._identifier = identifier
|
| 596 |
+
ctx._output_metadata = output_metadata
|
| 597 |
+
# We snapshot the dispatch keys in forward for materializing the
|
| 598 |
+
# the bw_graph in backward.
|
| 599 |
+
ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set()
|
| 600 |
+
ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set()
|
| 601 |
+
|
| 602 |
+
save_values_for_backward(ctx, operands)
|
| 603 |
+
|
| 604 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 605 |
+
out = invoke_subgraph(
|
| 606 |
+
subgraph,
|
| 607 |
+
f"fw_{identifier}",
|
| 608 |
+
*operands,
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
# Check that int (coming from symint) is at expected indexes.
|
| 612 |
+
for idx, o in enumerate(out):
|
| 613 |
+
if isinstance(o, int):
|
| 614 |
+
if idx not in output_metadata.indexes_with_symint:
|
| 615 |
+
raise AssertionError(
|
| 616 |
+
f"unexpected int output at index {idx}, not in indexes_with_symint"
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
return out
|
| 620 |
+
|
| 621 |
+
@staticmethod
|
| 622 |
+
def backward(
|
| 623 |
+
ctx,
|
| 624 |
+
*grad_outs,
|
| 625 |
+
):
|
| 626 |
+
from torch._dynamo.utils import dynamo_timed
|
| 627 |
+
|
| 628 |
+
subgraph = ctx._subgraph
|
| 629 |
+
identifier = ctx._identifier
|
| 630 |
+
output_metadata = ctx._output_metadata
|
| 631 |
+
primals = saved_values(ctx)
|
| 632 |
+
|
| 633 |
+
# Filter out grads that are None or do not require_grad. This was
|
| 634 |
+
# the assumption we made during the tracing of joint_graph.
|
| 635 |
+
filtered_grad_outs = []
|
| 636 |
+
for idx, o in enumerate(grad_outs):
|
| 637 |
+
if o is None:
|
| 638 |
+
if idx not in output_metadata.indexes_with_symint:
|
| 639 |
+
raise AssertionError(
|
| 640 |
+
f"unexpected None grad_out at index {idx}, not in indexes_with_symint"
|
| 641 |
+
)
|
| 642 |
+
elif idx in output_metadata.indexes_with_no_grad:
|
| 643 |
+
# Deliberately skip over the grad_outs which we know should be
|
| 644 |
+
# None because the corresponding fwd_out does not require_grad.
|
| 645 |
+
pass
|
| 646 |
+
else:
|
| 647 |
+
filtered_grad_outs.append(o)
|
| 648 |
+
filtered_grad_outs = tuple(filtered_grad_outs)
|
| 649 |
+
|
| 650 |
+
# Important note - Even though the forward graph can be same for
|
| 651 |
+
# different invoke_subgraphs, the backward graph can be different
|
| 652 |
+
# because the tangent strides can be different. So, here we cache on
|
| 653 |
+
# tangent_metadata in addition to identifier
|
| 654 |
+
from torch._guards import detect_fake_mode
|
| 655 |
+
from torch._subclasses._fake_tensor_utils import _CacheKeyState
|
| 656 |
+
from torch._subclasses.fake_tensor import extract_tensor_metadata
|
| 657 |
+
|
| 658 |
+
fake_mode = detect_fake_mode(primals + filtered_grad_outs)
|
| 659 |
+
if fake_mode is None:
|
| 660 |
+
raise AssertionError("fake_mode should be enabled for HOPs")
|
| 661 |
+
state = _CacheKeyState(fake_mode.shape_env)
|
| 662 |
+
|
| 663 |
+
tangent_metadata: list[object] = []
|
| 664 |
+
for tangent in filtered_grad_outs:
|
| 665 |
+
metadata = extract_tensor_metadata(tangent)
|
| 666 |
+
metadata._flatten_into(tangent_metadata, fake_mode, state)
|
| 667 |
+
|
| 668 |
+
# Add aliasing information to tangent_metadata
|
| 669 |
+
# Two tangents are aliased if they are the same tensor object (using id())
|
| 670 |
+
# We create a tuple of tuples where each inner tuple contains indices of aliased tensors
|
| 671 |
+
# e.g. ((0, 1),) would mean there is one aliasing group, and the first and second tangents are aliased
|
| 672 |
+
# e.g. () would mean there is no aliasing between tangents
|
| 673 |
+
tensor_to_indices: dict[int, list[int]] = defaultdict(list)
|
| 674 |
+
for i, tangent in enumerate(filtered_grad_outs):
|
| 675 |
+
if isinstance(tangent, torch.Tensor):
|
| 676 |
+
tensor_to_indices[id(tangent)].append(i)
|
| 677 |
+
|
| 678 |
+
aliasing_groups = tuple(
|
| 679 |
+
sorted(
|
| 680 |
+
tuple(indices)
|
| 681 |
+
for indices in tensor_to_indices.values()
|
| 682 |
+
if len(indices) > 1
|
| 683 |
+
)
|
| 684 |
+
)
|
| 685 |
+
tangent_metadata.append(aliasing_groups)
|
| 686 |
+
|
| 687 |
+
# pyrefly: ignore [bad-assignment]
|
| 688 |
+
tangent_metadata = tuple(tangent_metadata)
|
| 689 |
+
|
| 690 |
+
# bw_graph is a joint graph with signature (*primals_and_tangents) and
|
| 691 |
+
# returns (*grads_and_fw_outs). To get the grads, we use the num_fw_outs
|
| 692 |
+
# to extract the grads.
|
| 693 |
+
primals_and_tangents = primals + filtered_grad_outs
|
| 694 |
+
|
| 695 |
+
# Check if we have already traced the bwd subgraph.
|
| 696 |
+
bw_graph = None
|
| 697 |
+
suffix = None
|
| 698 |
+
invoke_subgraph_cache = get_invoke_subgraph_cache()
|
| 699 |
+
cache_hit = False
|
| 700 |
+
if invoke_subgraph_cache:
|
| 701 |
+
bw_graph, suffix = invoke_subgraph_cache.get_lazy_bwd_entry(
|
| 702 |
+
identifier, tangent_metadata
|
| 703 |
+
)
|
| 704 |
+
cache_hit = bw_graph is not None
|
| 705 |
+
|
| 706 |
+
if bw_graph is None:
|
| 707 |
+
if suffix is not None:
|
| 708 |
+
raise AssertionError(
|
| 709 |
+
f"suffix should be None when bw_graph is None, got {suffix}"
|
| 710 |
+
)
|
| 711 |
+
with dynamo_timed(
|
| 712 |
+
"invoke_subgraph_trace_joint_graph", log_pt2_compile_event=True
|
| 713 |
+
):
|
| 714 |
+
bw_graph = trace_joint_graph_as_bwd(
|
| 715 |
+
subgraph,
|
| 716 |
+
len(primals),
|
| 717 |
+
primals_and_tangents,
|
| 718 |
+
ctx._fw_include_key_set,
|
| 719 |
+
ctx._fw_exclude_key_set,
|
| 720 |
+
)
|
| 721 |
+
if (
|
| 722 |
+
hasattr(subgraph, "meta")
|
| 723 |
+
and "nested_region_config" in subgraph.meta
|
| 724 |
+
):
|
| 725 |
+
bw_graph.meta["nested_region_config"] = subgraph.meta[
|
| 726 |
+
"nested_region_config"
|
| 727 |
+
]
|
| 728 |
+
|
| 729 |
+
if invoke_subgraph_cache and not cache_hit:
|
| 730 |
+
suffix = invoke_subgraph_cache.add_lazy_bwd_entry(
|
| 731 |
+
identifier, tangent_metadata, bw_graph
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
grads = invoke_subgraph(
|
| 735 |
+
bw_graph, f"bw_{identifier}_{suffix}", *primals_and_tangents
|
| 736 |
+
)[: -output_metadata.num_fw_outs]
|
| 737 |
+
return None, None, None, *grads
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
@invoke_subgraph.py_autograd_impl
|
| 741 |
+
def _(subgraph, identifier, *operands):
|
| 742 |
+
# Check if we have already traced the subgraph.
|
| 743 |
+
invoke_subgraph_cache = get_invoke_subgraph_cache()
|
| 744 |
+
if invoke_subgraph_cache:
|
| 745 |
+
if saved_autograd_fn := invoke_subgraph_cache.get_autograd_key_entry(
|
| 746 |
+
identifier
|
| 747 |
+
):
|
| 748 |
+
return saved_autograd_fn(*operands)
|
| 749 |
+
|
| 750 |
+
output_metadata = get_output_metadata(subgraph, *operands)
|
| 751 |
+
|
| 752 |
+
def autograd_fn_callable(*args):
|
| 753 |
+
return InvokeSubgraphAutogradOp.apply(
|
| 754 |
+
subgraph, identifier, output_metadata, *args
|
| 755 |
+
)
|
| 756 |
+
|
| 757 |
+
# Save the autograd_fn_callable in the dispatch set cache.
|
| 758 |
+
if invoke_subgraph_cache:
|
| 759 |
+
invoke_subgraph_cache.add_autograd_key_entry(identifier, autograd_fn_callable)
|
| 760 |
+
|
| 761 |
+
return autograd_fn_callable(*operands)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
@invoke_subgraph.py_impl(DebugMode)
|
| 765 |
+
def _(debug_mode, subgraph, identifier, *operands):
|
| 766 |
+
# record HOP call
|
| 767 |
+
call = torch.utils._debug_mode._OpCall(
|
| 768 |
+
invoke_subgraph,
|
| 769 |
+
(identifier, *operands),
|
| 770 |
+
kwargs={},
|
| 771 |
+
call_depth=debug_mode.call_depth + 1,
|
| 772 |
+
stack=debug_mode.record_stack_trace,
|
| 773 |
+
)
|
| 774 |
+
debug_mode._record_call(call)
|
| 775 |
+
|
| 776 |
+
debug_mode.call_depth += 1
|
| 777 |
+
debug_mode._handle_annotate(f"[enter InvokeSubgraph HOP] {identifier}")
|
| 778 |
+
|
| 779 |
+
# If the HOP is dispatched from DebugMode, we should enable debug_mode
|
| 780 |
+
# for the subgraph call.
|
| 781 |
+
with debug_mode:
|
| 782 |
+
if getattr(subgraph, "_boxed_call", False):
|
| 783 |
+
result = subgraph(list(operands))
|
| 784 |
+
else:
|
| 785 |
+
result = subgraph(*operands)
|
| 786 |
+
debug_mode._handle_annotate(f"[exit InvokeSubgraph HOP] {identifier}")
|
| 787 |
+
debug_mode.call_depth -= 1
|
| 788 |
+
# record output of HOP
|
| 789 |
+
debug_mode._record_call_output(call, result)
|
| 790 |
+
return result
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
@invoke_subgraph.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 794 |
+
def _(subgraph, identifier, *operands):
|
| 795 |
+
from torch.utils._python_dispatch import _get_current_dispatch_mode
|
| 796 |
+
|
| 797 |
+
mode = _get_current_dispatch_mode()
|
| 798 |
+
|
| 799 |
+
if mode is not None:
|
| 800 |
+
raise AssertionError("Mode should never be enabled for CPU/CUDA key")
|
| 801 |
+
|
| 802 |
+
if getattr(subgraph, "_boxed_call", False):
|
| 803 |
+
return subgraph(list(operands))
|
| 804 |
+
else:
|
| 805 |
+
return subgraph(*operands)
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
@invoke_subgraph.py_functionalize_impl
|
| 809 |
+
def _(ctx, subgraph, identifier, *operands):
|
| 810 |
+
from torch._higher_order_ops.auto_functionalize import (
|
| 811 |
+
can_auto_functionalize,
|
| 812 |
+
do_auto_functionalize_v2,
|
| 813 |
+
)
|
| 814 |
+
|
| 815 |
+
# (in the functionalization metadata phase) Capture tokens before
|
| 816 |
+
tokens_before = dict(ctx.mode._tokens)
|
| 817 |
+
|
| 818 |
+
# Check if this subgraph has effects stored in the cache
|
| 819 |
+
invoke_subgraph_cache = get_invoke_subgraph_cache()
|
| 820 |
+
effects = None
|
| 821 |
+
if invoke_subgraph_cache:
|
| 822 |
+
effects = invoke_subgraph_cache.get_effects(identifier)
|
| 823 |
+
|
| 824 |
+
if effects:
|
| 825 |
+
if len(effects) != 1:
|
| 826 |
+
raise AssertionError(
|
| 827 |
+
f"Multiple effects within a subgraph NYI, got {len(effects)} effects"
|
| 828 |
+
)
|
| 829 |
+
tokens = ctx.mode._tokens
|
| 830 |
+
effects = next(iter(effects))
|
| 831 |
+
token_input = tokens[effects]
|
| 832 |
+
|
| 833 |
+
operands = (token_input, *operands)
|
| 834 |
+
|
| 835 |
+
def wrap_subgraph(subgraph):
|
| 836 |
+
def wrapped_subgraph(token, *args):
|
| 837 |
+
res = subgraph(*args)
|
| 838 |
+
return ctx.unwrap_tensors(ctx.mode._tokens[effects]), *res
|
| 839 |
+
|
| 840 |
+
return wrapped_subgraph
|
| 841 |
+
|
| 842 |
+
subgraph = wrap_subgraph(subgraph)
|
| 843 |
+
|
| 844 |
+
unwrapped_operands = ctx.unwrap_tensors(operands)
|
| 845 |
+
|
| 846 |
+
hop_instance = HopInstance.create(invoke_subgraph, subgraph, identifier, *operands)
|
| 847 |
+
if can_auto_functionalize(hop_instance):
|
| 848 |
+
# NOTE: [auto_functionalize x invoke_subgraph caching]
|
| 849 |
+
# We call auto_functionalized_v2 to support input mutation of invoke_subgraph.
|
| 850 |
+
# See NOTE [Support input mutation of hops] for the overall design.
|
| 851 |
+
#
|
| 852 |
+
# invoke_subgraph is special because of its identifier based caching mechanism.
|
| 853 |
+
# In invoke_subgraph's functionalization key implementation, we create a new
|
| 854 |
+
# identifier because the subgraph is replaced by FunctionWithNoFreeVars in a
|
| 855 |
+
# functional + epilogue form.
|
| 856 |
+
if not isinstance(identifier, str):
|
| 857 |
+
raise AssertionError(
|
| 858 |
+
f"identifier must be a string for auto_functionalize, got {type(identifier)}"
|
| 859 |
+
)
|
| 860 |
+
return do_auto_functionalize_v2(
|
| 861 |
+
ctx.mode,
|
| 862 |
+
hop_instance,
|
| 863 |
+
(subgraph, "auto_functionalized_" + identifier, *operands),
|
| 864 |
+
{},
|
| 865 |
+
)
|
| 866 |
+
|
| 867 |
+
with ctx.redispatch_to_next():
|
| 868 |
+
# NB: There is an assumption that subgraph does not mutate inputs and
|
| 869 |
+
# there is no aliasing. It's Dynamo's responsibility to prevent formation
|
| 870 |
+
# of invoke_subgraph ops if input aliasing/mutation is detected.
|
| 871 |
+
functionalized_subgraph = FunctionalizeCtxWrapper(ctx, subgraph)
|
| 872 |
+
out = invoke_subgraph(functionalized_subgraph, identifier, *unwrapped_operands)
|
| 873 |
+
|
| 874 |
+
if effects:
|
| 875 |
+
(new_token, *out) = out
|
| 876 |
+
ctx.mode._tokens[effects] = new_token
|
| 877 |
+
|
| 878 |
+
# (in the functionalization metadata phase) Capture tokens after and see if
|
| 879 |
+
# there are any differences (there are new effects or the token value for an
|
| 880 |
+
# effect type has changed)
|
| 881 |
+
tokens_after = dict(ctx.mode._tokens)
|
| 882 |
+
discovered_effects = set()
|
| 883 |
+
for effect_type, token in tokens_after.items():
|
| 884 |
+
if effect_type not in tokens_before or tokens_before[effect_type] is not token:
|
| 885 |
+
discovered_effects.add(effect_type)
|
| 886 |
+
|
| 887 |
+
if discovered_effects:
|
| 888 |
+
if not ctx.mode._allow_token_discovery:
|
| 889 |
+
raise AssertionError(
|
| 890 |
+
f"Number of tokens changed by {len(discovered_effects)} when tracing subgraph {subgraph}."
|
| 891 |
+
)
|
| 892 |
+
# Store discovered effects in the cache by identifier
|
| 893 |
+
if invoke_subgraph_cache:
|
| 894 |
+
invoke_subgraph_cache.add_effects(identifier, discovered_effects)
|
| 895 |
+
|
| 896 |
+
return ctx.wrap_tensors(out)
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
# Register the hop fake fn. This will be called in the fake_tensor _dispatch_impl.
|
| 900 |
+
@register_fake(invoke_subgraph)
|
| 901 |
+
def _(subgraph, identifier, *operands):
|
| 902 |
+
from torch._dynamo.utils import dynamo_timed
|
| 903 |
+
|
| 904 |
+
with dynamo_timed("invoke_subgraph_fake_tensor", log_pt2_compile_event=True):
|
| 905 |
+
if getattr(subgraph, "_boxed_call", False):
|
| 906 |
+
return subgraph(list(operands))
|
| 907 |
+
return subgraph(*operands)
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
@invoke_subgraph.py_impl(ProxyTorchDispatchMode)
|
| 911 |
+
def _(proxy_mode: ProxyTorchDispatchMode, subgraph, identifier, *operands):
|
| 912 |
+
# Check if we have already traced the subgraph.
|
| 913 |
+
graph = None
|
| 914 |
+
invoke_subgraph_cache = get_invoke_subgraph_cache()
|
| 915 |
+
if invoke_subgraph_cache:
|
| 916 |
+
graph = invoke_subgraph_cache.get_proxy_dispatch_entry(identifier)
|
| 917 |
+
|
| 918 |
+
if graph is None:
|
| 919 |
+
from torch._dynamo.utils import dynamo_timed
|
| 920 |
+
|
| 921 |
+
with dynamo_timed("invoke_subgraph_proxy_tensor", log_pt2_compile_event=True):
|
| 922 |
+
subgraph_decomp_table = _extract_nested_region_config(subgraph)
|
| 923 |
+
|
| 924 |
+
# NB: invoke_subgraph subgraph re-trace seq_nr
|
| 925 |
+
# The joint graph seq_nr will get wrong in the subsequent re-trace (all nodes will have the same seq_nr),
|
| 926 |
+
# so we preserve the original graph's seq_nr here.
|
| 927 |
+
with torch.fx.traceback._preserve_node_seq_nr():
|
| 928 |
+
graph = reenter_make_fx(
|
| 929 |
+
subgraph, subgraph_decomp_table=subgraph_decomp_table
|
| 930 |
+
)(*operands)
|
| 931 |
+
|
| 932 |
+
from torch._guards import detect_fake_mode
|
| 933 |
+
|
| 934 |
+
fake_mode = detect_fake_mode(operands)
|
| 935 |
+
# Only insert deferred runtime asserts when we have dynamic shapes.
|
| 936 |
+
# When shape_env is None (static shapes), there are no deferred asserts to insert.
|
| 937 |
+
if fake_mode is not None and fake_mode.shape_env is not None:
|
| 938 |
+
insert_deferred_runtime_asserts(
|
| 939 |
+
graph,
|
| 940 |
+
fake_mode.shape_env,
|
| 941 |
+
"invoke_subgraph_proxy_torch_dispatch_mode",
|
| 942 |
+
export=True,
|
| 943 |
+
)
|
| 944 |
+
graph.recompile()
|
| 945 |
+
|
| 946 |
+
if not isinstance(proxy_mode.tracer, torch.fx.Tracer):
|
| 947 |
+
raise AssertionError(
|
| 948 |
+
f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}"
|
| 949 |
+
)
|
| 950 |
+
if invoke_subgraph_cache:
|
| 951 |
+
invoke_subgraph_cache.add_proxy_dispatch_entry(identifier, graph)
|
| 952 |
+
|
| 953 |
+
node_args = (graph, identifier, *operands)
|
| 954 |
+
|
| 955 |
+
def _unwrap_proxy(arg):
|
| 956 |
+
if isinstance(arg, torch.fx.GraphModule):
|
| 957 |
+
# NOTE: [invoke_subgraph proxy_mode x auto_functionalize]
|
| 958 |
+
# Previously, we assumed that `invoke_subgraph` would always be traced with the same tracer.
|
| 959 |
+
# This allowed us to cache modules by their identifiers, assuming they were already registered.
|
| 960 |
+
#
|
| 961 |
+
# However, this assumption no longer holds when we auto-functionalize `invoke_subgraph`.
|
| 962 |
+
# auto_functionalize functionalizes the subgraph and wrap it with `FunctionWithNoFreeVars`.
|
| 963 |
+
# In the proxy mode implementation of `auto_functionalized_v2`, we need to materialize `FunctionWithNoFreeVars`
|
| 964 |
+
# input as a graph module. To do this, we re-trace the `invoke_subgraph` hop, which starts a new sub-tracer
|
| 965 |
+
# (see NOTE [materialize callable inputs as graph]). # When the new sub-tracer traces the `invoke_subgraph`
|
| 966 |
+
# with a previously cached identifier, the corresponding graph module might not
|
| 967 |
+
# exist as a submodule in the new tracer's root. Therefore, we register it as a submodule below.
|
| 968 |
+
#
|
| 969 |
+
# The alternative is to give a new identifier when we re-trace the invoke_subgraph but this will increase
|
| 970 |
+
# the compilation time, which defeats the purpose of caching.
|
| 971 |
+
registered_before = False
|
| 972 |
+
for (
|
| 973 |
+
_,
|
| 974 |
+
submod,
|
| 975 |
+
) in proxy_mode.tracer.root.named_modules(): # type: ignore[union-attr]
|
| 976 |
+
if arg is submod:
|
| 977 |
+
registered_before = True
|
| 978 |
+
|
| 979 |
+
if not registered_before:
|
| 980 |
+
qualname = proxy_mode.tracer.get_fresh_qualname("repeated_subgraph") # type: ignore[union-attr]
|
| 981 |
+
proxy_mode.tracer.root.register_module(qualname, arg) # type: ignore[union-attr]
|
| 982 |
+
return proxy_mode.tracer.unwrap_proxy(arg) # type: ignore[union-attr]
|
| 983 |
+
|
| 984 |
+
proxy_args = pytree.tree_map(_unwrap_proxy, node_args) # type: ignore[union-attr]
|
| 985 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 986 |
+
"call_function", invoke_subgraph, proxy_args, {}
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
example_out = invoke_subgraph(graph, identifier, *operands)
|
| 990 |
+
return track_tensor_tree(
|
| 991 |
+
example_out, out_proxy, constant=None, tracer=proxy_mode.tracer
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def invoke_subgraph_inductor_compile(
|
| 996 |
+
gm, example_inputs, inductor_config_patches=None, **kwargs
|
| 997 |
+
):
|
| 998 |
+
from torch._functorch._aot_autograd.runtime_wrappers import (
|
| 999 |
+
SerializableCompiledFunction,
|
| 1000 |
+
)
|
| 1001 |
+
from torch._functorch._aot_autograd.utils import simple_wraps
|
| 1002 |
+
from torch._inductor import config
|
| 1003 |
+
from torch._inductor.compile_fx import compile_fx_inner
|
| 1004 |
+
from torch._inductor.standalone_compile import AOTCompiledArtifact
|
| 1005 |
+
|
| 1006 |
+
# Used for testing only, should only be changed via _testing_capture_invoke_subgraph_inductor_compile_gms()
|
| 1007 |
+
if (
|
| 1008 |
+
torch._dynamo.testing._testing_invoke_subgraph_inductor_compile_captured_gms
|
| 1009 |
+
is not None
|
| 1010 |
+
):
|
| 1011 |
+
torch._dynamo.testing._testing_invoke_subgraph_inductor_compile_captured_gms.append(
|
| 1012 |
+
copy.deepcopy(gm)
|
| 1013 |
+
)
|
| 1014 |
+
|
| 1015 |
+
if inductor_config_patches is None:
|
| 1016 |
+
inductor_config_patches = {}
|
| 1017 |
+
compile_fn = config.patch(inductor_config_patches)(compile_fx_inner)
|
| 1018 |
+
compiled_fn_inner = compile_fn(gm, example_inputs)
|
| 1019 |
+
if not compiled_fn_inner._boxed_call:
|
| 1020 |
+
raise AssertionError(
|
| 1021 |
+
"compiled_fn_inner must have _boxed_call attribute set to True"
|
| 1022 |
+
)
|
| 1023 |
+
|
| 1024 |
+
# Follow boxed calling convention
|
| 1025 |
+
@simple_wraps(compiled_fn_inner)
|
| 1026 |
+
def forward(*runtime_args: tuple[Any]):
|
| 1027 |
+
full_args = []
|
| 1028 |
+
full_args.extend(runtime_args)
|
| 1029 |
+
return compiled_fn_inner(full_args)
|
| 1030 |
+
|
| 1031 |
+
# Just for convenience
|
| 1032 |
+
forward.zero_grad = gm.zero_grad # type: ignore[attr-defined]
|
| 1033 |
+
forward.named_parameters = gm.named_parameters # type: ignore[attr-defined]
|
| 1034 |
+
forward.named_buffers = gm.named_buffers # type: ignore[attr-defined]
|
| 1035 |
+
|
| 1036 |
+
# TODO: Do we need the post compile passes in _aot_stage2b_compile_forward_or_inference?
|
| 1037 |
+
# TODO: add a real serialize function for SerializableCompiledFunction like _cache_inference_info
|
| 1038 |
+
forward.serialize = SerializableCompiledFunction(forward, lambda: None) # type: ignore[attr-defined]
|
| 1039 |
+
return AOTCompiledArtifact(forward)
|
| 1040 |
+
|
| 1041 |
+
|
| 1042 |
+
def get_invoke_subgraph_compile_options(
|
| 1043 |
+
inductor_config_patches=None,
|
| 1044 |
+
decompositions=None,
|
| 1045 |
+
partitioner="min_cut_rematerialization_partition",
|
| 1046 |
+
):
|
| 1047 |
+
if inductor_config_patches is None:
|
| 1048 |
+
inductor_config_patches = {"triton.autotune_at_compile_time": True}
|
| 1049 |
+
inductor_compile = functools.partial(
|
| 1050 |
+
invoke_subgraph_inductor_compile,
|
| 1051 |
+
inductor_config_patches=inductor_config_patches,
|
| 1052 |
+
)
|
| 1053 |
+
|
| 1054 |
+
if inductor_config_patches:
|
| 1055 |
+
from torch._inductor import config as inductor_config
|
| 1056 |
+
|
| 1057 |
+
# Validate that all config keys exist
|
| 1058 |
+
for key in inductor_config_patches:
|
| 1059 |
+
if not hasattr(inductor_config, key):
|
| 1060 |
+
raise ValueError(
|
| 1061 |
+
f"Invalid inductor config key '{key}' in get_invoke_subgraph_compile_options. "
|
| 1062 |
+
f"Available config keys can be found in torch._inductor.config"
|
| 1063 |
+
)
|
| 1064 |
+
|
| 1065 |
+
return NestedCompileRegionOptions(
|
| 1066 |
+
fw_compiler=inductor_compile,
|
| 1067 |
+
bw_compiler=inductor_compile,
|
| 1068 |
+
partitioner=partitioner,
|
| 1069 |
+
decompositions=decompositions,
|
| 1070 |
+
)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/local_map.py
ADDED
|
@@ -0,0 +1,645 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
# NOTE: this file may be removed once we move to a dynamo frontend
|
| 7 |
+
|
| 8 |
+
import contextlib
|
| 9 |
+
import functools
|
| 10 |
+
from collections.abc import Callable, Generator, Sequence
|
| 11 |
+
from contextlib import contextmanager
|
| 12 |
+
from typing import Any, TypeAlias
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.utils._pytree as pytree
|
| 16 |
+
from torch._C import DispatchKey
|
| 17 |
+
from torch._higher_order_ops.utils import (
|
| 18 |
+
clone_outputs_aliasing_inputs,
|
| 19 |
+
redirect_to_mode,
|
| 20 |
+
save_values_for_backward,
|
| 21 |
+
saved_values,
|
| 22 |
+
)
|
| 23 |
+
from torch._ops import HigherOrderOperator
|
| 24 |
+
from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
|
| 25 |
+
from torch._subclasses.functional_tensor import FunctionalTensor
|
| 26 |
+
from torch.fx import GraphModule
|
| 27 |
+
from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
|
| 28 |
+
from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Proxy the HOP instead of inlining into it
|
| 32 |
+
# And trace it with local shapes for AP
|
| 33 |
+
_DEFER_INLINING = False
|
| 34 |
+
|
| 35 |
+
GraphArg: TypeAlias = tuple[torch.Tensor, int, torch.SymInt, None]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@contextmanager
|
| 39 |
+
def defer_inlining() -> Generator[None, None, None]:
|
| 40 |
+
global _DEFER_INLINING
|
| 41 |
+
prior = _DEFER_INLINING
|
| 42 |
+
try:
|
| 43 |
+
_DEFER_INLINING = True
|
| 44 |
+
yield
|
| 45 |
+
finally:
|
| 46 |
+
_DEFER_INLINING = prior
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# Used to unwrap tensors classes like FunctionalTensor and Parameter
|
| 50 |
+
def _new_tensor(
|
| 51 |
+
t: Any,
|
| 52 |
+
new_shape: Sequence[int] | None = None,
|
| 53 |
+
new_stride: Sequence[int] | None = None,
|
| 54 |
+
) -> Any:
|
| 55 |
+
if isinstance(t, torch.Tensor):
|
| 56 |
+
if type(t) not in (FunctionalTensor, FakeTensor, torch.Tensor):
|
| 57 |
+
raise AssertionError(f"No subclasses support for now, found {type(t)}")
|
| 58 |
+
return torch.empty_strided(
|
| 59 |
+
t.size() if new_shape is None else new_shape,
|
| 60 |
+
t.stride() if new_stride is None else new_stride,
|
| 61 |
+
device=t.device,
|
| 62 |
+
dtype=t.dtype,
|
| 63 |
+
requires_grad=t.requires_grad,
|
| 64 |
+
)
|
| 65 |
+
return t
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# Autoparallel specific, we want to treat plain tensors as DTensors
|
| 69 |
+
def _redistribute(
|
| 70 |
+
args: Any,
|
| 71 |
+
all_placements: tuple[Any],
|
| 72 |
+
mesh: Any,
|
| 73 |
+
shape_stride_fn: Callable[[torch.Tensor, Any, Any], tuple[list[int], list[int]]],
|
| 74 |
+
) -> GraphArg:
|
| 75 |
+
from torch._dispatch.python import suspend_functionalization
|
| 76 |
+
from torch._guards import detect_fake_mode
|
| 77 |
+
from torch._subclasses.functional_tensor import disable_functional_mode
|
| 78 |
+
from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing
|
| 79 |
+
|
| 80 |
+
with (
|
| 81 |
+
suspend_functionalization(),
|
| 82 |
+
disable_functional_mode(),
|
| 83 |
+
disable_proxy_modes_tracing(),
|
| 84 |
+
):
|
| 85 |
+
fake_mode = detect_fake_mode(args)
|
| 86 |
+
if fake_mode is None:
|
| 87 |
+
raise AssertionError("defer_inlining() is only supported for FakeTensors")
|
| 88 |
+
|
| 89 |
+
with fake_mode:
|
| 90 |
+
new_args = list(pytree.tree_map(_new_tensor, args))
|
| 91 |
+
for i, (tensor, placements) in enumerate(zip(new_args, all_placements)):
|
| 92 |
+
if tensor is None:
|
| 93 |
+
# Sometimes gradients can be None
|
| 94 |
+
continue
|
| 95 |
+
|
| 96 |
+
new_shape, new_stride = shape_stride_fn(
|
| 97 |
+
tensor,
|
| 98 |
+
mesh,
|
| 99 |
+
placements,
|
| 100 |
+
)
|
| 101 |
+
new_args[i] = _new_tensor(
|
| 102 |
+
tensor, new_shape=new_shape, new_stride=new_stride
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
new_args = tuple(new_args)
|
| 106 |
+
if not all(
|
| 107 |
+
isinstance(t, (FakeTensor, int, torch.SymInt, type(None)))
|
| 108 |
+
for t in new_args
|
| 109 |
+
):
|
| 110 |
+
raise AssertionError(f"Unexpected element in {args=}")
|
| 111 |
+
|
| 112 |
+
return new_args
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def redistribute_fw_inputs(
|
| 116 |
+
global_args: Any, all_placements: Any, mesh: Any, _: int | None = None
|
| 117 |
+
) -> GraphArg:
|
| 118 |
+
if len(global_args) != len(all_placements):
|
| 119 |
+
raise AssertionError(
|
| 120 |
+
f"global_args length ({len(global_args)}) != all_placements length ({len(all_placements)})"
|
| 121 |
+
)
|
| 122 |
+
return _redistribute(
|
| 123 |
+
global_args,
|
| 124 |
+
all_placements,
|
| 125 |
+
mesh,
|
| 126 |
+
torch.distributed.tensor._utils.compute_local_tensor_info,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def redistribute_fw_outputs(
|
| 131 |
+
local_outs: Any, all_placements: Any, mesh: Any, num_activations: int
|
| 132 |
+
) -> GraphArg:
|
| 133 |
+
if len(local_outs) != len(all_placements) + num_activations:
|
| 134 |
+
raise AssertionError(
|
| 135 |
+
f"local_outs length ({len(local_outs)}) != "
|
| 136 |
+
f"all_placements length ({len(all_placements)}) + num_activations ({num_activations})"
|
| 137 |
+
)
|
| 138 |
+
num_fw_outs = len(local_outs) - num_activations
|
| 139 |
+
if num_fw_outs <= 0:
|
| 140 |
+
raise AssertionError(f"num_fw_outs must be > 0, got {num_fw_outs}")
|
| 141 |
+
outs, activations = local_outs[:num_fw_outs], local_outs[num_fw_outs:]
|
| 142 |
+
return (
|
| 143 |
+
*_redistribute(
|
| 144 |
+
outs,
|
| 145 |
+
all_placements,
|
| 146 |
+
mesh,
|
| 147 |
+
torch.distributed.tensor._utils.compute_global_tensor_info,
|
| 148 |
+
),
|
| 149 |
+
*activations,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def redistribute_bw_inputs(
|
| 154 |
+
global_args: Any, all_placements: Any, mesh: Any, num_activations: int
|
| 155 |
+
) -> GraphArg:
|
| 156 |
+
if len(global_args) != len(all_placements) + num_activations:
|
| 157 |
+
raise AssertionError(
|
| 158 |
+
f"global_args length ({len(global_args)}) != "
|
| 159 |
+
f"all_placements length ({len(all_placements)}) + num_activations ({num_activations})"
|
| 160 |
+
)
|
| 161 |
+
activations, inputs = global_args[:num_activations], global_args[num_activations:]
|
| 162 |
+
if len(inputs) <= 0:
|
| 163 |
+
raise AssertionError("inputs must not be empty")
|
| 164 |
+
local_inputs = _redistribute(
|
| 165 |
+
inputs,
|
| 166 |
+
all_placements,
|
| 167 |
+
mesh,
|
| 168 |
+
torch.distributed.tensor._utils.compute_local_tensor_info,
|
| 169 |
+
)
|
| 170 |
+
return (
|
| 171 |
+
*activations,
|
| 172 |
+
*local_inputs,
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def redistribute_bw_outputs(
|
| 177 |
+
local_outs: Any, all_placements: Any, mesh: Any, _: int | None = None
|
| 178 |
+
) -> GraphArg:
|
| 179 |
+
if len(local_outs) != len(all_placements):
|
| 180 |
+
raise AssertionError(
|
| 181 |
+
f"local_outs length ({len(local_outs)}) != all_placements length ({len(all_placements)})"
|
| 182 |
+
)
|
| 183 |
+
return _redistribute(
|
| 184 |
+
local_outs,
|
| 185 |
+
all_placements,
|
| 186 |
+
mesh,
|
| 187 |
+
torch.distributed.tensor._utils.compute_global_tensor_info,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class LocalMapHOP(HigherOrderOperator):
|
| 192 |
+
def __init__(self) -> None:
|
| 193 |
+
super().__init__("local_map_hop")
|
| 194 |
+
|
| 195 |
+
def __call__(self, gm: GraphModule, *args: Any, **kwargs: Any) -> Any:
|
| 196 |
+
# pyrefly: ignore [missing-attribute]
|
| 197 |
+
return super().__call__(gm, *args, **kwargs)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
local_map_hop = LocalMapHOP()
|
| 201 |
+
|
| 202 |
+
# Registers dispatches for SAC
|
| 203 |
+
redirect_to_mode(local_map_hop, _CachingTorchDispatchMode)
|
| 204 |
+
redirect_to_mode(local_map_hop, _CachedTorchDispatchMode)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def create_hop_fw_bw(
|
| 208 |
+
fw_gm: GraphModule,
|
| 209 |
+
*_args: Any,
|
| 210 |
+
) -> tuple[GraphModule, GraphModule, int, int, set[int]]:
|
| 211 |
+
"""
|
| 212 |
+
Traces a joint, applies passes and partitions it
|
| 213 |
+
"""
|
| 214 |
+
# Keeping these imports here
|
| 215 |
+
# Avoid circular dependencies once we upstream with dynamo frontend
|
| 216 |
+
from torch._dispatch.python import suspend_functionalization
|
| 217 |
+
from torch._functorch.aot_autograd import AOTConfig, create_joint
|
| 218 |
+
from torch._guards import detect_fake_mode
|
| 219 |
+
from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
|
| 220 |
+
from torch._subclasses.functional_tensor import disable_functional_mode
|
| 221 |
+
from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing, make_fx
|
| 222 |
+
|
| 223 |
+
local_map_kwargs = fw_gm.meta["local_map_kwargs"] # type: ignore[attr-defined]
|
| 224 |
+
if "in_placements" not in local_map_kwargs:
|
| 225 |
+
raise AssertionError("'in_placements' not found in local_map_kwargs")
|
| 226 |
+
if "out_placements" not in local_map_kwargs:
|
| 227 |
+
raise AssertionError("'out_placements' not found in local_map_kwargs")
|
| 228 |
+
if "device_mesh" not in local_map_kwargs:
|
| 229 |
+
raise AssertionError("'device_mesh' not found in local_map_kwargs")
|
| 230 |
+
if len(local_map_kwargs["in_placements"]) != len(_args):
|
| 231 |
+
raise AssertionError(
|
| 232 |
+
f"in_placements length ({len(local_map_kwargs['in_placements'])}) != _args length ({len(_args)})"
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
dummy_aot_config = AOTConfig(
|
| 236 |
+
fw_compiler=None, # type: ignore[arg-type]
|
| 237 |
+
bw_compiler=None, # type: ignore[arg-type]
|
| 238 |
+
partition_fn=None, # type: ignore[arg-type]
|
| 239 |
+
decompositions={},
|
| 240 |
+
num_params_buffers=0,
|
| 241 |
+
aot_id=0,
|
| 242 |
+
keep_inference_input_mutations=False,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
with suspend_functionalization(), disable_functional_mode():
|
| 246 |
+
with disable_proxy_modes_tracing():
|
| 247 |
+
# If someone runs this hop under the default compiler backend ("eager")
|
| 248 |
+
# Then this path will be run with the actual user inputs. We convert them
|
| 249 |
+
# to fake tensors in order to not perform any actual compute.
|
| 250 |
+
|
| 251 |
+
fake_mode = detect_fake_mode(_args)
|
| 252 |
+
if fake_mode is None:
|
| 253 |
+
fake_mode = FakeTensorMode(allow_non_fake_inputs=True)
|
| 254 |
+
|
| 255 |
+
with fake_mode:
|
| 256 |
+
fw_inputs = redistribute_fw_inputs(
|
| 257 |
+
_args,
|
| 258 |
+
local_map_kwargs["in_placements"],
|
| 259 |
+
local_map_kwargs["device_mesh"],
|
| 260 |
+
)
|
| 261 |
+
if len(fw_inputs) != len(local_map_kwargs["in_placements"]):
|
| 262 |
+
raise AssertionError(
|
| 263 |
+
f"fw_inputs length ({len(fw_inputs)}) != "
|
| 264 |
+
f"in_placements length ({len(local_map_kwargs['in_placements'])})"
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
if not all(
|
| 268 |
+
isinstance(t, (FakeTensor, int, torch.SymInt)) for t in fw_inputs
|
| 269 |
+
):
|
| 270 |
+
raise AssertionError(f"Unexpected element in {fw_inputs=}")
|
| 271 |
+
|
| 272 |
+
ctx = (
|
| 273 |
+
fake_mode.shape_env.ignore_fresh_unbacked_symbols
|
| 274 |
+
if fake_mode.shape_env is not None
|
| 275 |
+
else contextlib.nullcontext
|
| 276 |
+
)
|
| 277 |
+
with ctx():
|
| 278 |
+
fw_outs = fw_gm(*fw_inputs)
|
| 279 |
+
|
| 280 |
+
example_grads = pytree.tree_map(
|
| 281 |
+
_new_tensor,
|
| 282 |
+
fw_outs,
|
| 283 |
+
)
|
| 284 |
+
if not isinstance(example_grads, (list, tuple)):
|
| 285 |
+
example_grads = [example_grads]
|
| 286 |
+
|
| 287 |
+
num_fw_inputs = len(fw_inputs)
|
| 288 |
+
num_fw_outputs = len(example_grads)
|
| 289 |
+
|
| 290 |
+
def joint_f(
|
| 291 |
+
*primals_and_tangents: list[torch.Tensor],
|
| 292 |
+
) -> Any:
|
| 293 |
+
primals = primals_and_tangents[:num_fw_inputs]
|
| 294 |
+
tangents = primals_and_tangents[num_fw_inputs:]
|
| 295 |
+
|
| 296 |
+
def prepare_fw_with_masks(
|
| 297 |
+
fw_gm: torch.fx.GraphModule,
|
| 298 |
+
) -> Callable[..., Any]:
|
| 299 |
+
def fw_with_masks(*args: Any) -> tuple[tuple[Any], list[bool]]:
|
| 300 |
+
# The Interpreter here is required to propagate metadata
|
| 301 |
+
# from the dynamo graph body to the local_map graph body.
|
| 302 |
+
# This is required for fx_traceback.annotate for work.
|
| 303 |
+
fw_out = torch.fx.Interpreter(fw_gm).run(*args)
|
| 304 |
+
if not isinstance(fw_out, tuple):
|
| 305 |
+
raise AssertionError(
|
| 306 |
+
"Dynamo traced submodule should return tuple"
|
| 307 |
+
)
|
| 308 |
+
return fw_out, [
|
| 309 |
+
bool(isinstance(ret, torch.Tensor) and ret.requires_grad)
|
| 310 |
+
for ret in fw_out
|
| 311 |
+
]
|
| 312 |
+
|
| 313 |
+
return fw_with_masks
|
| 314 |
+
|
| 315 |
+
fw_outs, grads = create_joint(
|
| 316 |
+
prepare_fw_with_masks(fw_gm), aot_config=dummy_aot_config
|
| 317 |
+
)(primals, tangents)
|
| 318 |
+
from torch.fx.experimental.symbolic_shapes import has_free_unbacked_symbols
|
| 319 |
+
|
| 320 |
+
if has_free_unbacked_symbols((*fw_outs, *grads)):
|
| 321 |
+
raise AssertionError(
|
| 322 |
+
"Unbacked symints leaking outside of the joint graph is not yet supported."
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents)
|
| 326 |
+
# put grads first to work with existing hop utils
|
| 327 |
+
return pytree.tree_map(maybe_clone, (*grads, *fw_outs))
|
| 328 |
+
|
| 329 |
+
filtered_grads_idx = set()
|
| 330 |
+
for i, example_grad in enumerate(example_grads):
|
| 331 |
+
# Filter out grads that are None or do not require_grad.
|
| 332 |
+
# The AOTAutograd utils we rely on force this assumption.
|
| 333 |
+
# We must also filter the runtime tangents too.
|
| 334 |
+
if example_grad is not None and (
|
| 335 |
+
isinstance(example_grad, torch.Tensor) and example_grad.requires_grad
|
| 336 |
+
):
|
| 337 |
+
filtered_grads_idx.add(i)
|
| 338 |
+
|
| 339 |
+
primals_and_tangents = [
|
| 340 |
+
*fw_inputs,
|
| 341 |
+
*[example_grads[i] for i in filtered_grads_idx],
|
| 342 |
+
]
|
| 343 |
+
joint_hop_gm = make_fx(joint_f)(*primals_and_tangents)
|
| 344 |
+
from torch._functorch._aot_autograd.graph_capture import (
|
| 345 |
+
copy_fwd_metadata_to_bw_nodes,
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
copy_fwd_metadata_to_bw_nodes(joint_hop_gm)
|
| 349 |
+
|
| 350 |
+
from torch._functorch._aot_autograd.graph_compile import prepare_for_partitioner
|
| 351 |
+
from torch._inductor.compile_fx import partition_fn
|
| 352 |
+
|
| 353 |
+
# Match partitioner convention
|
| 354 |
+
prepped_joint_hop_gm = prepare_for_partitioner(
|
| 355 |
+
joint_hop_gm, num_fw_inputs, num_fw_outputs
|
| 356 |
+
)
|
| 357 |
+
with disable_proxy_modes_tracing():
|
| 358 |
+
# Also runs joint passes
|
| 359 |
+
new_fw_gm, new_bw_gm = partition_fn(
|
| 360 |
+
prepped_joint_hop_gm,
|
| 361 |
+
[],
|
| 362 |
+
num_fwd_outputs=num_fw_outputs,
|
| 363 |
+
static_lifetime_input_indices=[],
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
# Fix tags because min-cut does not respect fw/bw boundary, breaking
|
| 367 |
+
# default partitioner's assumptions.
|
| 368 |
+
for node in new_fw_gm.graph.nodes:
|
| 369 |
+
node.meta["partitioner_tag"] = "is_forward"
|
| 370 |
+
for node in new_bw_gm.graph.nodes:
|
| 371 |
+
node.meta["partitioner_tag"] = "is_backward"
|
| 372 |
+
|
| 373 |
+
# Propagate meta onto fw/bw graphs, later will be set on proxied nodes
|
| 374 |
+
new_fw_gm.meta["local_map_kwargs"] = local_map_kwargs
|
| 375 |
+
new_bw_gm.meta["local_map_kwargs"] = {**local_map_kwargs}
|
| 376 |
+
# Okay because Autoparallel assumes same sharding between param and grads
|
| 377 |
+
new_bw_gm.meta["local_map_kwargs"]["in_placements"] = tuple(
|
| 378 |
+
[local_map_kwargs["out_placements"][i] for i in filtered_grads_idx]
|
| 379 |
+
)
|
| 380 |
+
new_bw_gm.meta["local_map_kwargs"]["out_placements"] = local_map_kwargs[
|
| 381 |
+
"in_placements"
|
| 382 |
+
]
|
| 383 |
+
|
| 384 |
+
# Validate Forward
|
| 385 |
+
fw_kwargs = new_fw_gm.meta["local_map_kwargs"]
|
| 386 |
+
expected_fw_inputs = len(fw_kwargs["in_placements"])
|
| 387 |
+
expected_fw_outputs = len(fw_kwargs["out_placements"])
|
| 388 |
+
actual_fw_inputs = len(new_fw_gm.graph.find_nodes(op="placeholder"))
|
| 389 |
+
actual_fw_outputs = num_fw_outputs
|
| 390 |
+
if expected_fw_inputs != actual_fw_inputs:
|
| 391 |
+
raise AssertionError(
|
| 392 |
+
f"expected_fw_inputs ({expected_fw_inputs}) != actual_fw_inputs ({actual_fw_inputs})"
|
| 393 |
+
)
|
| 394 |
+
if expected_fw_outputs != actual_fw_outputs:
|
| 395 |
+
raise AssertionError(
|
| 396 |
+
f"expected_fw_outputs ({expected_fw_outputs}) != actual_fw_outputs ({actual_fw_outputs})"
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
# Validate Activations
|
| 400 |
+
if len(new_fw_gm.graph.find_nodes(op="output")) != 1:
|
| 401 |
+
raise AssertionError(
|
| 402 |
+
f"Expected exactly 1 output node, got {len(new_fw_gm.graph.find_nodes(op='output'))}"
|
| 403 |
+
)
|
| 404 |
+
num_activations = (
|
| 405 |
+
len(new_fw_gm.graph.find_nodes(op="output")[0].args[0]) - num_fw_outputs
|
| 406 |
+
)
|
| 407 |
+
# tensors first, then symints
|
| 408 |
+
if num_activations < 0:
|
| 409 |
+
raise AssertionError(f"num_activations must be >= 0, got {num_activations}")
|
| 410 |
+
|
| 411 |
+
# Validate Backward
|
| 412 |
+
bw_kwargs = new_bw_gm.meta["local_map_kwargs"]
|
| 413 |
+
expected_bw_inputs = len(bw_kwargs["in_placements"])
|
| 414 |
+
expected_bw_outputs = len(bw_kwargs["out_placements"])
|
| 415 |
+
actual_bw_inputs = (
|
| 416 |
+
len(new_bw_gm.graph.find_nodes(op="placeholder")) - num_activations
|
| 417 |
+
)
|
| 418 |
+
if actual_bw_inputs <= 0:
|
| 419 |
+
raise AssertionError(
|
| 420 |
+
f"actual_bw_inputs must be > 0, got {actual_bw_inputs}"
|
| 421 |
+
)
|
| 422 |
+
if expected_fw_inputs + expected_bw_inputs != len(primals_and_tangents):
|
| 423 |
+
raise AssertionError(
|
| 424 |
+
f"expected_fw_inputs ({expected_fw_inputs}) + expected_bw_inputs ({expected_bw_inputs}) "
|
| 425 |
+
f"!= primals_and_tangents length ({len(primals_and_tangents)})"
|
| 426 |
+
)
|
| 427 |
+
if actual_fw_inputs + actual_bw_inputs != len(primals_and_tangents):
|
| 428 |
+
raise AssertionError(
|
| 429 |
+
f"actual_fw_inputs ({actual_fw_inputs}) + actual_bw_inputs ({actual_bw_inputs}) "
|
| 430 |
+
f"!= primals_and_tangents length ({len(primals_and_tangents)})"
|
| 431 |
+
)
|
| 432 |
+
if len(new_bw_gm.graph.find_nodes(op="output")) != 1:
|
| 433 |
+
raise AssertionError(
|
| 434 |
+
f"Expected exactly 1 bw output node, got {len(new_bw_gm.graph.find_nodes(op='output'))}"
|
| 435 |
+
)
|
| 436 |
+
actual_bw_outputs = len(new_bw_gm.graph.find_nodes(op="output")[0].args[0])
|
| 437 |
+
if expected_bw_inputs != actual_bw_inputs:
|
| 438 |
+
raise AssertionError(
|
| 439 |
+
f"expected_bw_inputs ({expected_bw_inputs}) != actual_bw_inputs ({actual_bw_inputs})"
|
| 440 |
+
)
|
| 441 |
+
if expected_bw_outputs != actual_bw_outputs:
|
| 442 |
+
raise AssertionError(
|
| 443 |
+
f"expected_bw_outputs ({expected_bw_outputs}) != actual_bw_outputs ({actual_bw_outputs})"
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
new_fw_gm.meta["num_activations"] = num_activations
|
| 447 |
+
new_fw_gm.meta["is_backward"] = False
|
| 448 |
+
new_bw_gm.meta["num_activations"] = num_activations
|
| 449 |
+
new_bw_gm.meta["is_backward"] = True
|
| 450 |
+
|
| 451 |
+
return new_fw_gm, new_bw_gm, num_fw_inputs, num_fw_outputs, filtered_grads_idx
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
class LocalMapAutogradOp(torch.autograd.Function):
|
| 455 |
+
@staticmethod
|
| 456 |
+
# pyrefly: ignore [bad-override]
|
| 457 |
+
def forward(
|
| 458 |
+
ctx: Any,
|
| 459 |
+
fw_gm: GraphModule,
|
| 460 |
+
bw_gm: GraphModule,
|
| 461 |
+
num_fw_ins: int,
|
| 462 |
+
num_fw_outs: int,
|
| 463 |
+
filtered_grads_idx: set[int],
|
| 464 |
+
*args: Any,
|
| 465 |
+
**kwargs: Any,
|
| 466 |
+
) -> tuple[torch.Tensor | None, ...]:
|
| 467 |
+
from torch._functorch._aot_autograd.schemas import MemoryFormatMeta
|
| 468 |
+
|
| 469 |
+
ctx.bw_gm = bw_gm
|
| 470 |
+
ctx.num_fw_ins = num_fw_ins
|
| 471 |
+
ctx.filtered_grads_idx = filtered_grads_idx
|
| 472 |
+
|
| 473 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 474 |
+
fw_outs_with_saved_activations = local_map_hop(fw_gm, *args, **kwargs)
|
| 475 |
+
|
| 476 |
+
fw_outs = fw_outs_with_saved_activations[:num_fw_outs]
|
| 477 |
+
saved_activations = fw_outs_with_saved_activations[num_fw_outs:]
|
| 478 |
+
save_values_for_backward(ctx, saved_activations)
|
| 479 |
+
|
| 480 |
+
# Force memory_format path (not exact size/stride) because local_map forward
|
| 481 |
+
# operates on local shapes but backward receives global-shaped tangents.
|
| 482 |
+
# TODO(ivankobzarev): Support exact size/stride by converting between local/global shapes.
|
| 483 |
+
ctx.expected_tangent_metadata = {
|
| 484 |
+
i: MemoryFormatMeta.from_tensor(fw_outs[i], force_use_memory_format=True)
|
| 485 |
+
for i in filtered_grads_idx
|
| 486 |
+
}
|
| 487 |
+
return fw_outs
|
| 488 |
+
|
| 489 |
+
@staticmethod
|
| 490 |
+
def backward(
|
| 491 |
+
ctx: Any, *_grads: tuple[torch.Tensor]
|
| 492 |
+
) -> tuple[torch.Tensor | None, ...]:
|
| 493 |
+
from torch._functorch._aot_autograd.runtime_wrappers import (
|
| 494 |
+
coerce_to_expected_memory_format,
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
if ctx.pos != sorted(ctx.pos):
|
| 498 |
+
raise AssertionError(
|
| 499 |
+
"Interleaving saved tensor activations and symints is not expected from min-cut partitioner."
|
| 500 |
+
)
|
| 501 |
+
ctx.pos = list(reversed(ctx.pos)) # make saved_values return symints first
|
| 502 |
+
saved_activations = saved_values(ctx)
|
| 503 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 504 |
+
# Filter out grads that are None or do not require_grad.
|
| 505 |
+
# The AOTAutograd utils we rely on force this assumption.
|
| 506 |
+
grads = [_grads[i] for i in ctx.filtered_grads_idx]
|
| 507 |
+
if len(grads) != len(ctx.expected_tangent_metadata):
|
| 508 |
+
raise AssertionError(
|
| 509 |
+
f"{len(grads)=} vs {len(ctx.expected_tangent_metadata)}"
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
for i, meta in ctx.expected_tangent_metadata.items():
|
| 513 |
+
grads[i] = coerce_to_expected_memory_format(grads[i], meta)
|
| 514 |
+
|
| 515 |
+
grad_ins = local_map_hop(ctx.bw_gm, *saved_activations, *grads)
|
| 516 |
+
if len(grad_ins) != ctx.num_fw_ins:
|
| 517 |
+
raise RuntimeError(
|
| 518 |
+
f"Expected {ctx.num_fw_ins} grad_ins, got {len(grad_ins)}"
|
| 519 |
+
)
|
| 520 |
+
return None, None, None, None, None, *grad_ins
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
@local_map_hop.py_impl(torch._C.DispatchKey.Autograd)
|
| 524 |
+
def autograd_key(
|
| 525 |
+
fw_gm: GraphModule,
|
| 526 |
+
*args: Any,
|
| 527 |
+
**kwargs: Any,
|
| 528 |
+
) -> Any:
|
| 529 |
+
local_map_kwargs = fw_gm.meta["local_map_kwargs"] # type: ignore[attr-defined]
|
| 530 |
+
if local_map_kwargs.get("in_grad_placements", None) is not None:
|
| 531 |
+
raise AssertionError("local_map in_grad_placements are not yet supported.")
|
| 532 |
+
if _DEFER_INLINING:
|
| 533 |
+
fw_gm, bw_gm, num_fw_ins, num_fw_outs, filtered_grads_idx = create_hop_fw_bw(
|
| 534 |
+
fw_gm, *args
|
| 535 |
+
)
|
| 536 |
+
return LocalMapAutogradOp.apply(
|
| 537 |
+
fw_gm, bw_gm, num_fw_ins, num_fw_outs, filtered_grads_idx, *args, **kwargs
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
# TODO: get rid of this when we can install as a subgraph
|
| 541 |
+
return torch.fx.Interpreter(fw_gm).run(*args, **kwargs)
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
@local_map_hop.py_functionalize_impl
|
| 545 |
+
def functional_mode_key(
|
| 546 |
+
ctx: Any, gm: GraphModule, *args: Any, **kwargs: Any
|
| 547 |
+
) -> tuple[torch.Tensor]:
|
| 548 |
+
if kwargs:
|
| 549 |
+
raise AssertionError(f"kwargs must be empty, got {kwargs}")
|
| 550 |
+
|
| 551 |
+
unwrapped_inputs = ctx.unwrap_tensors(args)
|
| 552 |
+
with ctx.redispatch_to_next():
|
| 553 |
+
out = local_map_hop(gm, *unwrapped_inputs)
|
| 554 |
+
return ctx.wrap_tensors(out)
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
@local_map_hop.py_impl(FakeTensorMode)
|
| 558 |
+
def fake_mode_key(
|
| 559 |
+
mode: FakeTensorMode,
|
| 560 |
+
gm: GraphModule,
|
| 561 |
+
*args: Any,
|
| 562 |
+
**kwargs: Any,
|
| 563 |
+
) -> GraphArg:
|
| 564 |
+
with mode:
|
| 565 |
+
if not _DEFER_INLINING:
|
| 566 |
+
return gm(*args, **kwargs)
|
| 567 |
+
|
| 568 |
+
# otherwise, we need to convert to local shapes for AP
|
| 569 |
+
is_backward = gm.meta["is_backward"]
|
| 570 |
+
redistribute_inputs = (
|
| 571 |
+
redistribute_bw_inputs if is_backward else redistribute_fw_inputs
|
| 572 |
+
)
|
| 573 |
+
local_args = redistribute_inputs(
|
| 574 |
+
args,
|
| 575 |
+
gm.meta["local_map_kwargs"]["in_placements"],
|
| 576 |
+
gm.meta["local_map_kwargs"]["device_mesh"],
|
| 577 |
+
gm.meta["num_activations"],
|
| 578 |
+
)
|
| 579 |
+
local_outs = gm(*local_args)
|
| 580 |
+
redistribute_outputs = (
|
| 581 |
+
redistribute_bw_outputs if is_backward else redistribute_fw_outputs
|
| 582 |
+
)
|
| 583 |
+
global_outs = redistribute_outputs(
|
| 584 |
+
local_outs,
|
| 585 |
+
gm.meta["local_map_kwargs"]["out_placements"],
|
| 586 |
+
gm.meta["local_map_kwargs"]["device_mesh"],
|
| 587 |
+
gm.meta["num_activations"],
|
| 588 |
+
)
|
| 589 |
+
return global_outs
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def proxy_mode_key_common(
|
| 593 |
+
call_hop: Callable[..., Any],
|
| 594 |
+
proxy_mode: ProxyTorchDispatchMode,
|
| 595 |
+
gm: GraphModule,
|
| 596 |
+
*args: Any,
|
| 597 |
+
**kwargs: Any,
|
| 598 |
+
) -> tuple[torch.Tensor]:
|
| 599 |
+
if proxy_mode is None:
|
| 600 |
+
raise AssertionError("Mode should always be enabled for python fallback key")
|
| 601 |
+
if len(kwargs) != 0:
|
| 602 |
+
raise AssertionError(f"kwargs must be empty, got {kwargs}")
|
| 603 |
+
|
| 604 |
+
example_out = call_hop(*args, **kwargs)
|
| 605 |
+
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) # type: ignore[union-attr]
|
| 606 |
+
|
| 607 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 608 |
+
"call_function", call_hop, proxy_args, {}
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
# extract local_map args, post-dispatch operates on GraphModules
|
| 612 |
+
if not gm.meta["local_map_kwargs"]:
|
| 613 |
+
raise AssertionError("gm.meta['local_map_kwargs'] must be set")
|
| 614 |
+
local_map_kwargs = gm.meta["local_map_kwargs"]
|
| 615 |
+
|
| 616 |
+
# propagate local_map args to the call_function node
|
| 617 |
+
out_proxy.node.meta["local_map_kwargs"] = local_map_kwargs
|
| 618 |
+
|
| 619 |
+
return track_tensor_tree(
|
| 620 |
+
example_out, out_proxy, constant=None, tracer=proxy_mode.tracer
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
@local_map_hop.py_impl(ProxyTorchDispatchMode)
|
| 625 |
+
def proxy_mode_key(
|
| 626 |
+
proxy_mode: ProxyTorchDispatchMode,
|
| 627 |
+
gm: GraphModule,
|
| 628 |
+
*args: Any,
|
| 629 |
+
**kwargs: Any,
|
| 630 |
+
) -> tuple[torch.Tensor]:
|
| 631 |
+
# TODO: get rid of this when we can install as a subgraph
|
| 632 |
+
def call_local_map(*_args: Any, **_kwargs: Any) -> Any:
|
| 633 |
+
return functools.partial(local_map_hop, gm)(*_args, **_kwargs)
|
| 634 |
+
|
| 635 |
+
return proxy_mode_key_common(call_local_map, proxy_mode, gm, *args, **kwargs)
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
# Running HOP in eager with real tensors
|
| 639 |
+
@local_map_hop.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 640 |
+
def real_impl(
|
| 641 |
+
gm: GraphModule,
|
| 642 |
+
*args: Any,
|
| 643 |
+
**kwargs: Any,
|
| 644 |
+
) -> tuple[torch.Tensor]:
|
| 645 |
+
return gm(*args, **kwargs)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/map.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
from collections.abc import Callable
|
| 4 |
+
from typing_extensions import TypeVarTuple
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.utils._pytree as pytree
|
| 8 |
+
from torch._C import DispatchKey
|
| 9 |
+
from torch._dispatch.python import suspend_functionalization
|
| 10 |
+
from torch._higher_order_ops.utils import _maybe_run_with_interpreter, reenter_make_fx
|
| 11 |
+
from torch._ops import HigherOrderOperator
|
| 12 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 13 |
+
from torch._subclasses.functional_tensor import disable_functional_mode
|
| 14 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 15 |
+
disable_proxy_modes_tracing,
|
| 16 |
+
ProxyTorchDispatchMode,
|
| 17 |
+
track_tensor_tree,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
from .utils import (
|
| 21 |
+
_from_fun,
|
| 22 |
+
_stack_pytree,
|
| 23 |
+
_unstack_pytree,
|
| 24 |
+
create_bw_fn,
|
| 25 |
+
fill_none_with_masks,
|
| 26 |
+
filter_with_masks,
|
| 27 |
+
first_slice_copy,
|
| 28 |
+
materialize_as_graph,
|
| 29 |
+
save_values_for_backward,
|
| 30 |
+
saved_values,
|
| 31 |
+
split_into_chunks,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class MapImpl(HigherOrderOperator):
|
| 36 |
+
def __init__(self):
|
| 37 |
+
super().__init__("map_impl")
|
| 38 |
+
|
| 39 |
+
def __call__(self, *args, **kwargs):
|
| 40 |
+
# pyrefly: ignore [missing-attribute]
|
| 41 |
+
return super().__call__(*args, **kwargs)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
map_impl = MapImpl()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def map(
|
| 48 |
+
f: Callable[[pytree.PyTree, tuple[pytree.PyTree, ...]], pytree.PyTree],
|
| 49 |
+
xs: pytree.PyTree | torch.Tensor,
|
| 50 |
+
*args: TypeVarTuple,
|
| 51 |
+
):
|
| 52 |
+
r"""
|
| 53 |
+
Performs a map of f with xs. Intuitively, you can think of the semantic being::
|
| 54 |
+
|
| 55 |
+
out = []
|
| 56 |
+
for idx in len(xs.size(0)):
|
| 57 |
+
xs_sliced = xs.select(0, idx)
|
| 58 |
+
out.append(f(xs_sliced, *args))
|
| 59 |
+
torch.stack(out)
|
| 60 |
+
|
| 61 |
+
.. warning::
|
| 62 |
+
|
| 63 |
+
``torch._higher_order_ops.map`` is a prototype feature in PyTorch. It currently
|
| 64 |
+
does not support autograd and you may run into miscompiles.
|
| 65 |
+
Read more about feature classification at:
|
| 66 |
+
https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
f (Callable): a callable that takes an input x, that could either be a single Tensor
|
| 71 |
+
or a nested dict, list of tensors and some additional inputs
|
| 72 |
+
xs: the inputs that're to be mapped over. We'll iterate over the first dim of each x
|
| 73 |
+
and perform f on each slice.
|
| 74 |
+
|
| 75 |
+
*args: additional arguments provided to each step of f. They could also be omitted and
|
| 76 |
+
map is able to automatically figure out the read dependency.
|
| 77 |
+
|
| 78 |
+
Return:
|
| 79 |
+
the stacked output for each step of f
|
| 80 |
+
|
| 81 |
+
Example::
|
| 82 |
+
|
| 83 |
+
def f(xs):
|
| 84 |
+
return xs[0] + xs[1] + const1 + const2
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
xs = [torch.randn(2, 3), torch.randn(2, 3)]
|
| 88 |
+
const1 = torch.randn(2, 3)
|
| 89 |
+
const2 = torch.randn(2, 3)
|
| 90 |
+
# returns a tensor of shape [2, 2, 3]
|
| 91 |
+
torch._higher_order_ops.map(f, xs)
|
| 92 |
+
|
| 93 |
+
"""
|
| 94 |
+
flat_xs, xs_spec = pytree.tree_flatten(xs)
|
| 95 |
+
flat_args, args_spec = pytree.tree_flatten(args)
|
| 96 |
+
if not all(isinstance(t, torch.Tensor) for t in flat_xs):
|
| 97 |
+
raise RuntimeError(f"Mapped xs can only consist of tensors. Got xs {flat_xs}.")
|
| 98 |
+
|
| 99 |
+
shapes = [xs.shape for xs in flat_xs]
|
| 100 |
+
leading_dim_size = shapes[0][0]
|
| 101 |
+
if leading_dim_size == 0:
|
| 102 |
+
raise RuntimeError("Leading dimensions of mapped xs cannot be 0.")
|
| 103 |
+
|
| 104 |
+
if any(cur_shape[0] != leading_dim_size for cur_shape in shapes):
|
| 105 |
+
raise RuntimeError(
|
| 106 |
+
f"Leading dimensions of mapped xs must be consistent. Got shapes {shapes}."
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
def run_flattened_map(f, flat_xs, flat_args):
|
| 110 |
+
def wrapped_fn(*flat_args, f, xs_tree_spec, args_tree_spec, num_xs):
|
| 111 |
+
xs = pytree.tree_unflatten(flat_args[:num_xs], xs_tree_spec)
|
| 112 |
+
args = pytree.tree_unflatten(flat_args[num_xs:], args_tree_spec)
|
| 113 |
+
return f(xs, *args)
|
| 114 |
+
|
| 115 |
+
inner_f = functools.partial(
|
| 116 |
+
wrapped_fn,
|
| 117 |
+
f=f,
|
| 118 |
+
xs_tree_spec=xs_spec,
|
| 119 |
+
args_tree_spec=args_spec,
|
| 120 |
+
num_xs=len(flat_xs),
|
| 121 |
+
)
|
| 122 |
+
return map_impl(inner_f, flat_xs, flat_args)
|
| 123 |
+
|
| 124 |
+
from torch._higher_order_ops.utils import _maybe_compile_and_run_fn
|
| 125 |
+
|
| 126 |
+
return _maybe_compile_and_run_fn(run_flattened_map, f, flat_xs, flat_args)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class MapAutogradOp(torch.autograd.Function):
|
| 130 |
+
@staticmethod
|
| 131 |
+
# pyrefly: ignore [bad-override]
|
| 132 |
+
def forward(ctx, f, num_mapped_args, *flat_args):
|
| 133 |
+
ctx._f = f
|
| 134 |
+
ctx._num_mapped_args = num_mapped_args
|
| 135 |
+
ctx._num_pos_args = len(flat_args) - num_mapped_args
|
| 136 |
+
|
| 137 |
+
# We snapshot the dispatch keys in forward for materializing the
|
| 138 |
+
# the bw_graph in backward.
|
| 139 |
+
ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set()
|
| 140 |
+
ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set()
|
| 141 |
+
save_values_for_backward(ctx, flat_args)
|
| 142 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 143 |
+
return (
|
| 144 |
+
*map_impl(f, flat_args[:num_mapped_args], flat_args[num_mapped_args:]),
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
@staticmethod
|
| 148 |
+
def backward(ctx, *flat_grads):
|
| 149 |
+
fw_args = saved_values(ctx)
|
| 150 |
+
num_mapped_args = ctx._num_mapped_args
|
| 151 |
+
num_pos_args = ctx._num_pos_args
|
| 152 |
+
num_grads = len(flat_grads)
|
| 153 |
+
|
| 154 |
+
fw_mapped_args, pos_args = split_into_chunks(
|
| 155 |
+
fw_args,
|
| 156 |
+
[
|
| 157 |
+
num_mapped_args,
|
| 158 |
+
num_pos_args,
|
| 159 |
+
],
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
bw_f = create_bw_fn(ctx._f, fw_args)
|
| 163 |
+
|
| 164 |
+
grads_tensor_masks = []
|
| 165 |
+
|
| 166 |
+
# Create a wrapper around thefor the bw_f
|
| 167 |
+
def bw_f_wrapper(*args):
|
| 168 |
+
nonlocal grads_tensor_masks
|
| 169 |
+
|
| 170 |
+
# Dissect args and re-order them for the ``ctx._bw_f``
|
| 171 |
+
# args provided to the wrapper are composed of [*fw_mapped_args, *flat_grads, *pos_args]
|
| 172 |
+
# The content of ``bw_f_tangents`` are the upstream gradients, i.e. flat_grads
|
| 173 |
+
# The content of ``bw_f_primals`` are the fw_args, i.e., [*fw_mapped_args, *pos_args]
|
| 174 |
+
# The bw_f requires *bw_f_primals, *bw_f_tangents
|
| 175 |
+
fw_m_args, bw_f_tangents, pos_args = split_into_chunks(
|
| 176 |
+
args, [num_mapped_args, num_grads, num_pos_args]
|
| 177 |
+
)
|
| 178 |
+
bw_f_primals = *fw_m_args, *pos_args
|
| 179 |
+
gradients = bw_f(*bw_f_primals, *bw_f_tangents)
|
| 180 |
+
grads_tensor_masks = [
|
| 181 |
+
True if isinstance(out, torch.Tensor) else out for out in gradients
|
| 182 |
+
]
|
| 183 |
+
return filter_with_masks(gradients, grads_tensor_masks)
|
| 184 |
+
|
| 185 |
+
def construct_args_single_step_bw():
|
| 186 |
+
unwrapped_mapped_xs = pytree.tree_map(_from_fun, fw_mapped_args)
|
| 187 |
+
# Use first_slice_copy instead of _unstack_pytree to avoid
|
| 188 |
+
# iterating over batch dim, which would guard on symbolic sizes.
|
| 189 |
+
example_xs = [
|
| 190 |
+
first_slice_copy(x).requires_grad_(x.requires_grad)
|
| 191 |
+
for x in unwrapped_mapped_xs
|
| 192 |
+
]
|
| 193 |
+
unwrapped_grads = pytree.tree_map(_from_fun, flat_grads)
|
| 194 |
+
example_grads = [
|
| 195 |
+
first_slice_copy(x).requires_grad_(x.requires_grad)
|
| 196 |
+
for x in unwrapped_grads
|
| 197 |
+
]
|
| 198 |
+
example_pos_args = [
|
| 199 |
+
_from_fun(arg) if isinstance(arg, torch.Tensor) else arg
|
| 200 |
+
for arg in pos_args
|
| 201 |
+
]
|
| 202 |
+
return *example_xs, *example_grads, *example_pos_args
|
| 203 |
+
|
| 204 |
+
with suspend_functionalization(), disable_functional_mode():
|
| 205 |
+
with disable_proxy_modes_tracing():
|
| 206 |
+
args_single_step_bw = construct_args_single_step_bw()
|
| 207 |
+
|
| 208 |
+
# TODO: we need to materialize the bw graphs because dynamo is unable to
|
| 209 |
+
# trace through the joint function when torch.compile torch.autograd.grad.
|
| 210 |
+
fn_bw_gm = materialize_as_graph(
|
| 211 |
+
bw_f_wrapper,
|
| 212 |
+
args_single_step_bw,
|
| 213 |
+
ctx._fw_include_key_set,
|
| 214 |
+
ctx._fw_exclude_key_set,
|
| 215 |
+
force_enable_grad=True,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
grads = map_impl(fn_bw_gm, fw_mapped_args + flat_grads, pos_args)
|
| 219 |
+
|
| 220 |
+
return None, None, *fill_none_with_masks(grads, grads_tensor_masks)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _broadcast_to_batch(output, batch_size):
|
| 224 |
+
"""Expand each tensor in output pytree to include batch dimension.
|
| 225 |
+
|
| 226 |
+
Note: Although outputs are flattened in the compiled path (via torch.compile),
|
| 227 |
+
users may call map_impl directly with pytree outputs, so we support pytrees
|
| 228 |
+
for backward compatibility.
|
| 229 |
+
"""
|
| 230 |
+
|
| 231 |
+
def expand_with_batch(t):
|
| 232 |
+
if isinstance(t, torch.Tensor):
|
| 233 |
+
# Use contiguous_format to match torch.stack behavior
|
| 234 |
+
return (
|
| 235 |
+
t.unsqueeze(0)
|
| 236 |
+
.expand(batch_size, *t.shape)
|
| 237 |
+
.clone(memory_format=torch.contiguous_format)
|
| 238 |
+
)
|
| 239 |
+
return t
|
| 240 |
+
|
| 241 |
+
return pytree.tree_map(expand_with_batch, output)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def trace_map(proxy_mode, func_overload, f, xs, pos_args):
|
| 245 |
+
from torch._higher_order_ops.utils import first_slice_copy
|
| 246 |
+
|
| 247 |
+
with disable_proxy_modes_tracing():
|
| 248 |
+
# Use first_slice_copy instead of _unstack_pytree to avoid
|
| 249 |
+
# iterating over batch dim, which would guard on symbolic sizes.
|
| 250 |
+
example_input = pytree.tree_map(first_slice_copy, xs)
|
| 251 |
+
|
| 252 |
+
body_graph = f
|
| 253 |
+
|
| 254 |
+
body_graph = reenter_make_fx(body_graph)(*example_input, *pos_args)
|
| 255 |
+
|
| 256 |
+
next_name = proxy_mode.tracer.get_fresh_qualname("body_graph_")
|
| 257 |
+
|
| 258 |
+
proxy_mode.tracer.root.register_module(next_name, body_graph)
|
| 259 |
+
|
| 260 |
+
fake_outs = map_impl(body_graph, xs, pos_args)
|
| 261 |
+
|
| 262 |
+
node_args = (body_graph, list(xs), list(pos_args))
|
| 263 |
+
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
|
| 264 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 265 |
+
"call_function", func_overload, proxy_args, {}, name="map_impl"
|
| 266 |
+
)
|
| 267 |
+
return track_tensor_tree(
|
| 268 |
+
fake_outs, out_proxy, constant=None, tracer=proxy_mode.tracer
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
@map_impl.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 273 |
+
def map_dense(f, xs, pos_args):
|
| 274 |
+
pytrees = [f(*inp, *pos_args) for inp in _unstack_pytree(xs)]
|
| 275 |
+
return _stack_pytree(pytrees)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
@map_impl.py_autograd_impl
|
| 279 |
+
def map_autograd(f, xs, pos_args):
|
| 280 |
+
num_mapped_args = len(xs)
|
| 281 |
+
flat_out = MapAutogradOp.apply(f, num_mapped_args, *xs, *pos_args)
|
| 282 |
+
return flat_out
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
@map_impl.py_impl(ProxyTorchDispatchMode)
|
| 286 |
+
def map_proxy_torch_dispatch_mode(mode, f, xs, args):
|
| 287 |
+
return trace_map(mode, map_impl, f, xs, args)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
@map_impl.py_impl(FakeTensorMode)
|
| 291 |
+
def map_fake_tensor_mode(mode, f, xs, args):
|
| 292 |
+
from torch._higher_order_ops.utils import first_slice_copy
|
| 293 |
+
|
| 294 |
+
with mode:
|
| 295 |
+
# Use first_slice_copy instead of _unstack_pytree to avoid
|
| 296 |
+
# iterating over batch dim, which would guard on symbolic sizes.
|
| 297 |
+
first_row = pytree.tree_map(first_slice_copy, xs)
|
| 298 |
+
example_output = f(*first_row, *args)
|
| 299 |
+
|
| 300 |
+
flat_xs, _ = pytree.tree_flatten(xs)
|
| 301 |
+
batch_size = flat_xs[0].shape[0]
|
| 302 |
+
|
| 303 |
+
return _broadcast_to_batch(example_output, batch_size)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@map_impl.py_functionalize_impl
|
| 307 |
+
def map_functionalize(ctx, f, xs, pos_args):
|
| 308 |
+
from torch._higher_order_ops.utils import (
|
| 309 |
+
_check_alias_and_mutation,
|
| 310 |
+
first_slice_copy,
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
unwrapped_xs = ctx.unwrap_tensors(xs)
|
| 314 |
+
unwrapped_args = ctx.unwrap_tensors(pos_args)
|
| 315 |
+
wrapped_fn = ctx.functionalize(_maybe_run_with_interpreter(f))
|
| 316 |
+
|
| 317 |
+
with ctx.redispatch_to_next():
|
| 318 |
+
# Use first_slice_copy instead of _unstack_pytree to avoid
|
| 319 |
+
# iterating over batch dim, which would guard on symbolic sizes.
|
| 320 |
+
example_inputs = (
|
| 321 |
+
*pytree.tree_map(first_slice_copy, unwrapped_xs),
|
| 322 |
+
*unwrapped_args,
|
| 323 |
+
)
|
| 324 |
+
pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
|
| 325 |
+
_check_alias_and_mutation(f, example_inputs, "map", pre_dispatch)
|
| 326 |
+
map_return = map_impl(wrapped_fn, unwrapped_xs, unwrapped_args)
|
| 327 |
+
return ctx.wrap_tensors(map_return)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _fake_map(f, x, *args):
|
| 331 |
+
from functorch.experimental.control_flow import _stack_pytree, _unstack_pytree
|
| 332 |
+
|
| 333 |
+
x_pytrees = _unstack_pytree(x)
|
| 334 |
+
zs = []
|
| 335 |
+
for xp in x_pytrees:
|
| 336 |
+
zs.append(f(xp, *args))
|
| 337 |
+
return _stack_pytree(zs)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/out_dtype.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.utils._pytree as pytree
|
| 5 |
+
from torch._C import DispatchKey
|
| 6 |
+
from torch._higher_order_ops.utils import autograd_not_implemented
|
| 7 |
+
from torch._ops import HigherOrderOperator
|
| 8 |
+
from torch._prims_common import elementwise_dtypes, ELEMENTWISE_TYPE_PROMOTION_KIND
|
| 9 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 10 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 11 |
+
disable_proxy_modes_tracing,
|
| 12 |
+
maybe_handle_decomp,
|
| 13 |
+
ProxyTorchDispatchMode,
|
| 14 |
+
track_tensor_tree,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# TODO to figure out a more generic approach
|
| 19 |
+
ALLOWABLE_OPS = [
|
| 20 |
+
torch.ops.aten.linear.default,
|
| 21 |
+
torch.ops.aten.mm.default,
|
| 22 |
+
torch.ops.aten.conv2d.default,
|
| 23 |
+
torch.ops.aten.convolution.default,
|
| 24 |
+
torch.ops.aten.mul.Tensor,
|
| 25 |
+
torch.ops.aten.mul.Scalar,
|
| 26 |
+
torch.ops.aten.div.Tensor,
|
| 27 |
+
torch.ops.aten.div.Scalar,
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class OutDtypeOperator(HigherOrderOperator):
|
| 32 |
+
"""
|
| 33 |
+
The out_dtype operator takes an existing ATen functional operator, an
|
| 34 |
+
`out_dtype` argument, and arguments to the original operator, and executes
|
| 35 |
+
the original operator and returns a Tensor with the `out_dtype` precision.
|
| 36 |
+
This operator does not mandate a compute precision so it allows the
|
| 37 |
+
representation to not be opinionated about the exact implementation.
|
| 38 |
+
|
| 39 |
+
The general implementation for all operators will be the following:
|
| 40 |
+
1. Promote inputs dtypes based on default PyTorch dtype promotion rules,
|
| 41 |
+
using the dtypes of all input Tensors/Scalars and the `out_dtype`
|
| 42 |
+
arugument.
|
| 43 |
+
2. Execute the operator
|
| 44 |
+
3. Cast the output to `out_dtype`
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(self) -> None:
|
| 48 |
+
super().__init__("out_dtype")
|
| 49 |
+
|
| 50 |
+
def __call__(self, op, output_dtype, *args):
|
| 51 |
+
if not isinstance(op, torch._ops.OpOverload):
|
| 52 |
+
raise ValueError("out_dtype's first argument must be an OpOverload")
|
| 53 |
+
if op._schema.is_mutable:
|
| 54 |
+
raise ValueError(
|
| 55 |
+
"out_dtype's first argument needs to be a functional operator"
|
| 56 |
+
)
|
| 57 |
+
if not (
|
| 58 |
+
len(op._schema.returns) == 1
|
| 59 |
+
and isinstance(op._schema.returns[0].type, torch.TensorType)
|
| 60 |
+
):
|
| 61 |
+
raise ValueError(
|
| 62 |
+
"out_dtype's can only apply to ops that return a single tensor"
|
| 63 |
+
f"Instead got {[r.type for r in op._schema.returns]}"
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
if op not in ALLOWABLE_OPS:
|
| 67 |
+
raise ValueError(
|
| 68 |
+
f"out_dtype only allows the following operators: {ALLOWABLE_OPS}."
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# pyrefly: ignore [missing-attribute]
|
| 72 |
+
res = super().__call__(op, output_dtype, *args)
|
| 73 |
+
|
| 74 |
+
return res
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
out_dtype = OutDtypeOperator()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def trace_out_dtype(proxy_mode, func_overload, op, output_dtype, *args):
|
| 81 |
+
# NB: Long-term we should put the decomposition logic into
|
| 82 |
+
# ProxyTorchDispatchMode so that people do not need to call maybe_handle_decomp
|
| 83 |
+
# in all HigherOrderOp proxy implementations.
|
| 84 |
+
r = maybe_handle_decomp(proxy_mode, func_overload, (op, output_dtype, *args), {})
|
| 85 |
+
if r is not NotImplemented:
|
| 86 |
+
return r
|
| 87 |
+
|
| 88 |
+
with disable_proxy_modes_tracing():
|
| 89 |
+
# This is a simplified implementation of this operator just for tracing.
|
| 90 |
+
# Actual implementation may also first promote the arguments
|
| 91 |
+
out = op(*args).to(dtype=output_dtype)
|
| 92 |
+
|
| 93 |
+
node_args = (op, output_dtype, *args)
|
| 94 |
+
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
|
| 95 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 96 |
+
"call_function", func_overload, proxy_args, {}, name="out_dtype"
|
| 97 |
+
)
|
| 98 |
+
return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@out_dtype.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 102 |
+
def out_dtype_dense(op: torch._ops.OpOverload, output_dtype: torch.dtype, *args):
|
| 103 |
+
if is_int_mm(op, output_dtype, args):
|
| 104 |
+
return torch._int_mm(*args)
|
| 105 |
+
return out_dtype_fallback(op, output_dtype, *args)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def is_int_mm(op, output_dtype, args):
|
| 109 |
+
return (
|
| 110 |
+
op is torch.ops.aten.mm.default
|
| 111 |
+
and output_dtype == torch.int32
|
| 112 |
+
and len(args) == 2
|
| 113 |
+
and args[0].dtype == torch.int8
|
| 114 |
+
and args[1].dtype == torch.int8
|
| 115 |
+
and (args[0].is_cuda or args[0].is_xpu)
|
| 116 |
+
and (args[1].is_cuda or args[1].is_xpu)
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def out_dtype_fallback(op, output_dtype, *args):
|
| 121 |
+
flat_inputs = pytree.arg_tree_leaves(*args) + [torch.ones(1, dtype=output_dtype)]
|
| 122 |
+
promote_dtype: torch.dtype = elementwise_dtypes(
|
| 123 |
+
*flat_inputs,
|
| 124 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 125 |
+
)[0]
|
| 126 |
+
|
| 127 |
+
casted_args = pytree.tree_map_only(
|
| 128 |
+
torch.Tensor, lambda arg: arg.to(dtype=promote_dtype), args
|
| 129 |
+
)
|
| 130 |
+
res = op(*casted_args).to(dtype=output_dtype)
|
| 131 |
+
return res
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
out_dtype.py_autograd_impl(autograd_not_implemented(out_dtype, deferred_error=True))
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@out_dtype.py_impl(ProxyTorchDispatchMode)
|
| 138 |
+
def out_dtype_proxy(
|
| 139 |
+
mode: ProxyTorchDispatchMode,
|
| 140 |
+
op: torch._ops.OpOverload,
|
| 141 |
+
output_dtype: torch.dtype,
|
| 142 |
+
*args,
|
| 143 |
+
):
|
| 144 |
+
return trace_out_dtype(mode, out_dtype, op, output_dtype, *args)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@out_dtype.py_impl(FakeTensorMode)
|
| 148 |
+
def out_dtype_fake_tensor_mode(
|
| 149 |
+
mode: FakeTensorMode,
|
| 150 |
+
op: torch._ops.OpOverload,
|
| 151 |
+
output_dtype: torch.dtype,
|
| 152 |
+
*args,
|
| 153 |
+
):
|
| 154 |
+
with mode:
|
| 155 |
+
return out_dtype_dense(op, output_dtype, *args)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@out_dtype.py_functionalize_impl
|
| 159 |
+
def out_dtype_func(ctx, op, output_dtype, *args):
|
| 160 |
+
unwrapped_args = tuple(ctx.unwrap_tensors(arg) for arg in args)
|
| 161 |
+
|
| 162 |
+
with ctx.redispatch_to_next():
|
| 163 |
+
res = out_dtype(op, output_dtype, *unwrapped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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch._higher_order_ops.utils import create_bw_fn, materialize_as_graph
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
logger: logging.Logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
logger.setLevel(logging.DEBUG)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _find_hop_subgraph_outputs(gm: torch.fx.GraphModule) -> tuple[torch.fx.Node]:
|
| 15 |
+
output_node_args = gm.graph.find_nodes(op="output")[0].args
|
| 16 |
+
if not isinstance(output_node_args, tuple):
|
| 17 |
+
raise AssertionError(
|
| 18 |
+
f"expected output_node_args to be tuple, got {type(output_node_args)}"
|
| 19 |
+
)
|
| 20 |
+
return output_node_args[0]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def is_complex_expr(expr: Any) -> bool:
|
| 24 |
+
return not expr.is_symbol and not expr.is_constant()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class HopPartitionedGraph:
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
fw_gm: torch.fx.GraphModule,
|
| 31 |
+
bw_gm: torch.fx.GraphModule,
|
| 32 |
+
n_fw_outputs: int,
|
| 33 |
+
n_intermediates: int,
|
| 34 |
+
no_complex_exprs_at_boundary: bool,
|
| 35 |
+
):
|
| 36 |
+
self.fw_gm = fw_gm
|
| 37 |
+
self.bw_gm = bw_gm
|
| 38 |
+
self.n_fw_outputs = n_fw_outputs
|
| 39 |
+
self.n_intermediates = n_intermediates
|
| 40 |
+
self.no_complex_exprs_at_boundary = no_complex_exprs_at_boundary
|
| 41 |
+
self._reorder_fw_output()
|
| 42 |
+
self._check_partition_boundary()
|
| 43 |
+
|
| 44 |
+
def _check_partition_boundary(self) -> None:
|
| 45 |
+
"""check partitioned graph is in valid state."""
|
| 46 |
+
invalid_reasons = []
|
| 47 |
+
fw_outputs = _find_hop_subgraph_outputs(self.fw_gm)
|
| 48 |
+
for i, out in enumerate(fw_outputs):
|
| 49 |
+
if "val" not in out.meta:
|
| 50 |
+
invalid_reasons.append(f"fw_gm output[{i}] doesn't have a 'val' meta.")
|
| 51 |
+
elif not isinstance(out.meta["val"], (torch.SymInt, torch.Tensor)):
|
| 52 |
+
invalid_reasons.append(
|
| 53 |
+
f"fw_gm output[{i}] is of type {type(out.meta['val'])} but only SymInt or Tensor are allowed."
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
elif (
|
| 57 |
+
isinstance(out.meta["val"], torch.SymInt)
|
| 58 |
+
and is_complex_expr(out.meta["val"].node.expr)
|
| 59 |
+
and self.no_complex_exprs_at_boundary
|
| 60 |
+
):
|
| 61 |
+
invalid_reasons.append(
|
| 62 |
+
f"fw_gm output[{i}] must be of type SymInt with basic symbols or "
|
| 63 |
+
f"Tensor but got {type(out.meta['val'])} {out.meta['val']}"
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
if len(fw_outputs) != self.n_fw_outputs + self.n_intermediates:
|
| 67 |
+
invalid_reasons.append(
|
| 68 |
+
f"len(fw_outputs) ({len(fw_outputs)}) != n_fw_outputs ({self.n_fw_outputs}) + n_intermediates ({self.n_intermediates})" # noqa: B950
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
bw_phs = list(self.bw_gm.graph.find_nodes(op="placeholder"))
|
| 72 |
+
|
| 73 |
+
if len(fw_outputs) != len(bw_phs):
|
| 74 |
+
invalid_reasons.append(
|
| 75 |
+
f"Expect number of fw_gm's output to be the same as bw_gm's input but "
|
| 76 |
+
f"fw_gm has {len(fw_outputs)} outputs, bw_gm takes {len(bw_phs)} inputs."
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
original_forward_outputs = fw_outputs[: self.n_fw_outputs]
|
| 80 |
+
fw_intermediates = fw_outputs[self.n_fw_outputs :]
|
| 81 |
+
|
| 82 |
+
bw_intermediates = bw_phs[: -self.n_fw_outputs]
|
| 83 |
+
bw_grads = bw_phs[-self.n_fw_outputs :]
|
| 84 |
+
|
| 85 |
+
def _match_size_or_expr(
|
| 86 |
+
val1: torch.SymInt | torch.Tensor,
|
| 87 |
+
val2: torch.SymInt | torch.Tensor,
|
| 88 |
+
) -> bool:
|
| 89 |
+
if type(val1) is not type(val2):
|
| 90 |
+
return False
|
| 91 |
+
|
| 92 |
+
if isinstance(val1, torch.SymInt) and isinstance(val2, torch.SymInt):
|
| 93 |
+
return val1.node.expr == val2.node.expr
|
| 94 |
+
elif isinstance(val1, torch.Tensor) and isinstance(val2, torch.Tensor):
|
| 95 |
+
return val1.size() == val2.size()
|
| 96 |
+
|
| 97 |
+
return False
|
| 98 |
+
|
| 99 |
+
for fw, bw in zip(fw_intermediates, bw_intermediates):
|
| 100 |
+
if fw.name != bw.name or not _match_size_or_expr(
|
| 101 |
+
fw.meta["val"], bw.meta["val"]
|
| 102 |
+
):
|
| 103 |
+
invalid_reasons.append("fw intermediates don't match bw intermediates")
|
| 104 |
+
|
| 105 |
+
for fw_out, bw_grad in zip(original_forward_outputs, bw_grads):
|
| 106 |
+
if not _match_size_or_expr(fw_out.meta["val"], bw_grad.meta["val"]):
|
| 107 |
+
invalid_reasons.append("fw outputs don't match bw gradients")
|
| 108 |
+
|
| 109 |
+
if len(invalid_reasons) > 0:
|
| 110 |
+
newline = "\n"
|
| 111 |
+
raise RuntimeError(
|
| 112 |
+
f"Invalid HopPartitionedGraph. Reasons:\n{newline.join(invalid_reasons)}"
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def _reorder_fw_output(self) -> None:
|
| 116 |
+
"""
|
| 117 |
+
Before the pass, fw_gm returns (*fw_outputs, *intermediates1)
|
| 118 |
+
and bw_gm takes (*intermediates2, *grad_fw_outputs) as input.
|
| 119 |
+
intermediates1 and intermediates2 share the same node names but
|
| 120 |
+
they might be in different order. E.g. this could happen if there
|
| 121 |
+
are inputs that contain symints.
|
| 122 |
+
|
| 123 |
+
To simplify downstream processing, this graph pass normalizes the output of fw_gm
|
| 124 |
+
to be consistent with the bacwkard inputs:
|
| 125 |
+
|
| 126 |
+
fw_gm:
|
| 127 |
+
- input: fw_args
|
| 128 |
+
- output: (*fw_outputs, *intermediates)
|
| 129 |
+
|
| 130 |
+
bw_gm:
|
| 131 |
+
- input: (*intermediates, *grad_fw_outputs)
|
| 132 |
+
- output: grad_fw_args
|
| 133 |
+
|
| 134 |
+
Example:
|
| 135 |
+
|
| 136 |
+
def fw_gm(x, y, z):
|
| 137 |
+
a, b, c = f(x), g(y), k(z)
|
| 138 |
+
return a, b, c, f_tmp, g_tmp, k_tmp
|
| 139 |
+
|
| 140 |
+
, where a, b, c are fw_outputs, f_tmp, g_tmp, k_tmp are intermediates
|
| 141 |
+
|
| 142 |
+
The corresponding bw_gm has the following signature:
|
| 143 |
+
|
| 144 |
+
def bw_gm(f_tmp, g_tmp, k_tmp, grad_a, grad_b, grac):
|
| 145 |
+
return grad_x, grad_y, grad_z
|
| 146 |
+
"""
|
| 147 |
+
fw_gm_output_nodes = _find_hop_subgraph_outputs(self.fw_gm)
|
| 148 |
+
fw_outputs_nodes = fw_gm_output_nodes[: self.n_fw_outputs]
|
| 149 |
+
fw_intermediates_nodes = fw_gm_output_nodes[self.n_fw_outputs :]
|
| 150 |
+
if len(fw_intermediates_nodes) > 0:
|
| 151 |
+
fw_intermediates_name_to_node = {n.name: n for n in fw_intermediates_nodes}
|
| 152 |
+
|
| 153 |
+
# First n_intermediates placeholders
|
| 154 |
+
bw_names: list[str] = [
|
| 155 |
+
ph.name
|
| 156 |
+
for ph in list(self.bw_gm.graph.find_nodes(op="placeholder"))[
|
| 157 |
+
: self.n_intermediates
|
| 158 |
+
]
|
| 159 |
+
]
|
| 160 |
+
new_fw_outputs = list(fw_outputs_nodes) + [
|
| 161 |
+
fw_intermediates_name_to_node[name] for name in bw_names
|
| 162 |
+
]
|
| 163 |
+
|
| 164 |
+
output_node = self.fw_gm.graph.find_nodes(op="output")[0]
|
| 165 |
+
output_node.args = (tuple(new_fw_outputs),)
|
| 166 |
+
|
| 167 |
+
self.fw_gm.graph.lint()
|
| 168 |
+
self.fw_gm.recompile()
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class HopJointGraph:
|
| 172 |
+
def __init__(
|
| 173 |
+
self,
|
| 174 |
+
joint_gm: torch.fx.GraphModule,
|
| 175 |
+
n_primals: int,
|
| 176 |
+
n_fw_outputs: int,
|
| 177 |
+
*,
|
| 178 |
+
functionalized: bool,
|
| 179 |
+
):
|
| 180 |
+
self.joint_gm = joint_gm
|
| 181 |
+
self.n_primals = n_primals
|
| 182 |
+
self.n_fw_outputs = n_fw_outputs
|
| 183 |
+
self.functionalized = functionalized
|
| 184 |
+
|
| 185 |
+
self._rename_phs()
|
| 186 |
+
self._remove_redundant_sym_size_ops()
|
| 187 |
+
|
| 188 |
+
def _rename_phs(self) -> None:
|
| 189 |
+
"""
|
| 190 |
+
Rename the placeholders for joint_gm so that the partitioner
|
| 191 |
+
could recognize which inputs are primals and which are tangents.
|
| 192 |
+
"""
|
| 193 |
+
self.n_tangents = 0
|
| 194 |
+
for i, ph in enumerate(self.joint_gm.graph.find_nodes(op="placeholder")):
|
| 195 |
+
if i < self.n_primals:
|
| 196 |
+
ph.target = f"primals_{i}"
|
| 197 |
+
ph.name = f"primals_{i}"
|
| 198 |
+
else:
|
| 199 |
+
self.n_tangents += 1
|
| 200 |
+
ph.target = f"tangents_{i - self.n_primals}"
|
| 201 |
+
ph.name = f"tangents_{i - self.n_primals}"
|
| 202 |
+
|
| 203 |
+
self.joint_gm.graph.lint()
|
| 204 |
+
self.joint_gm.compile()
|
| 205 |
+
|
| 206 |
+
def _remove_redundant_sym_size_ops(self) -> None:
|
| 207 |
+
"""
|
| 208 |
+
Deletes torch.ops.sym_size.int operators whose output is a
|
| 209 |
+
corresponding placeholder that holds the same symbol, and replace all usage
|
| 210 |
+
of the sym_size node to be directly using the placeholders.
|
| 211 |
+
|
| 212 |
+
This is to make sure all basic symbols come from inputs.
|
| 213 |
+
"""
|
| 214 |
+
placeholder_exprs = {}
|
| 215 |
+
for node in self.joint_gm.graph.nodes:
|
| 216 |
+
if (
|
| 217 |
+
isinstance(node, torch.fx.Node)
|
| 218 |
+
and node.op == "placeholder"
|
| 219 |
+
and hasattr(node, "meta")
|
| 220 |
+
and "val" in node.meta
|
| 221 |
+
):
|
| 222 |
+
val = node.meta["val"]
|
| 223 |
+
if isinstance(val, torch.SymInt):
|
| 224 |
+
placeholder_exprs[val.node.expr] = node
|
| 225 |
+
|
| 226 |
+
nodes_to_remove = []
|
| 227 |
+
for node in self.joint_gm.graph.find_nodes(
|
| 228 |
+
op="call_function", target=torch.ops.aten.sym_size.int
|
| 229 |
+
):
|
| 230 |
+
if not (hasattr(node, "meta") and "val" in node.meta):
|
| 231 |
+
raise AssertionError(
|
| 232 |
+
f"node {node} must have 'meta' attribute with 'val' key"
|
| 233 |
+
)
|
| 234 |
+
val = node.meta["val"]
|
| 235 |
+
expr = val.node.expr
|
| 236 |
+
if expr in placeholder_exprs:
|
| 237 |
+
placeholder_node = placeholder_exprs[expr]
|
| 238 |
+
node.replace_all_uses_with(placeholder_node)
|
| 239 |
+
nodes_to_remove.append(node)
|
| 240 |
+
|
| 241 |
+
for node in nodes_to_remove:
|
| 242 |
+
self.joint_gm.graph.erase_node(node)
|
| 243 |
+
|
| 244 |
+
self.joint_gm.graph.lint()
|
| 245 |
+
self.joint_gm.recompile()
|
| 246 |
+
|
| 247 |
+
def _mark_complex_exprs_as_must_recompute(self) -> None:
|
| 248 |
+
"""
|
| 249 |
+
For control flow operators such as scan, we don't want to
|
| 250 |
+
have symint in the partitioning boundaries because otherwise we would need to support stacking
|
| 251 |
+
the symints up, which causes more entropy in the stack.
|
| 252 |
+
|
| 253 |
+
By marking the recompute polify for complex nodes as MUST_RECOMPUTE, the partitioning boundary
|
| 254 |
+
no longer contains complex expressions.
|
| 255 |
+
|
| 256 |
+
Note that this pass doesn't exclude basic symbols from partitioning boundary
|
| 257 |
+
and it's up to the downstream to decide whether to return the basic symbol
|
| 258 |
+
or have a separate graph pass to remove them.
|
| 259 |
+
"""
|
| 260 |
+
|
| 261 |
+
from torch._functorch.partitioners import CheckpointPolicy
|
| 262 |
+
|
| 263 |
+
for n in (
|
| 264 |
+
node for node in self.joint_gm.graph.nodes if node.op == "call_function"
|
| 265 |
+
):
|
| 266 |
+
if "val" not in n.meta:
|
| 267 |
+
continue
|
| 268 |
+
val = n.meta["val"]
|
| 269 |
+
if isinstance(val, torch.SymInt) and is_complex_expr(val.node.expr):
|
| 270 |
+
if n.meta.get("recompute", None) is not None:
|
| 271 |
+
raise AssertionError(
|
| 272 |
+
f"node {n} with complex SymInt expression should not have recompute policy set"
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
n.meta["recompute"] = CheckpointPolicy.MUST_RECOMPUTE
|
| 276 |
+
|
| 277 |
+
self.joint_gm.graph.lint()
|
| 278 |
+
self.joint_gm.recompile()
|
| 279 |
+
|
| 280 |
+
def partition(
|
| 281 |
+
self, partition_fn: Callable, always_recompute_complex_exprs: bool
|
| 282 |
+
) -> HopPartitionedGraph:
|
| 283 |
+
if logger.isEnabledFor(logging.DEBUG):
|
| 284 |
+
logger.debug(
|
| 285 |
+
"before min_cut_partition:\n%s",
|
| 286 |
+
self.joint_gm.print_readable(print_output=False),
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
if always_recompute_complex_exprs:
|
| 290 |
+
self._mark_complex_exprs_as_must_recompute()
|
| 291 |
+
|
| 292 |
+
fw_gm, bw_gm = partition_fn(
|
| 293 |
+
self.joint_gm, None, num_fwd_outputs=self.n_fw_outputs
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
if logger.isEnabledFor(logging.DEBUG):
|
| 297 |
+
logger.debug("after partition_fn:")
|
| 298 |
+
logger.debug("fw_gm:\n%s", fw_gm.print_readable(print_output=False))
|
| 299 |
+
logger.debug("bw_gm:\n%s", bw_gm.print_readable(print_output=False))
|
| 300 |
+
|
| 301 |
+
n_intermediates = len(_find_hop_subgraph_outputs(fw_gm)) - self.n_fw_outputs
|
| 302 |
+
|
| 303 |
+
return HopPartitionedGraph(
|
| 304 |
+
fw_gm,
|
| 305 |
+
bw_gm,
|
| 306 |
+
self.n_fw_outputs,
|
| 307 |
+
n_intermediates,
|
| 308 |
+
always_recompute_complex_exprs,
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def create_hop_joint_graph(
|
| 313 |
+
fw_fn: Callable,
|
| 314 |
+
fw_args: tuple[torch.Tensor | torch.SymInt, ...],
|
| 315 |
+
functionalize: bool,
|
| 316 |
+
) -> HopJointGraph:
|
| 317 |
+
fw_gm = materialize_as_graph(fw_fn, fw_args, force_enable_grad=True)
|
| 318 |
+
fw_gm_output_nodes = _find_hop_subgraph_outputs(fw_gm)
|
| 319 |
+
|
| 320 |
+
if not all(
|
| 321 |
+
isinstance(n, torch.fx.Node) and "val" in n.meta for n in fw_gm_output_nodes
|
| 322 |
+
):
|
| 323 |
+
raise AssertionError(
|
| 324 |
+
"all fw_gm output nodes must be torch.fx.Node with 'val' in meta"
|
| 325 |
+
)
|
| 326 |
+
fw_gm_output_vals = tuple(n.meta["val"] for n in fw_gm_output_nodes) # type: ignore[arg-type]
|
| 327 |
+
|
| 328 |
+
if not all(isinstance(val, torch.Tensor) for val in fw_gm_output_vals):
|
| 329 |
+
raise AssertionError(
|
| 330 |
+
f"all fw_gm output values must be torch.Tensor, got {[type(v) for v in fw_gm_output_vals]}"
|
| 331 |
+
)
|
| 332 |
+
example_grads = tuple(torch.zeros_like(val) for val in fw_gm_output_vals)
|
| 333 |
+
|
| 334 |
+
joint_fn = create_bw_fn(fw_fn, fw_args, return_fw_outputs=True)
|
| 335 |
+
joint_gm = materialize_as_graph(
|
| 336 |
+
joint_fn, fw_args + example_grads, force_enable_grad=True
|
| 337 |
+
)
|
| 338 |
+
if functionalize:
|
| 339 |
+
# Need to first trace out the joint_fn with autograd info on
|
| 340 |
+
# then functionalize the graph otherwise the grad information is lost
|
| 341 |
+
joint_gm = materialize_as_graph(
|
| 342 |
+
# pyrefly: ignore [bad-argument-type]
|
| 343 |
+
torch.func.functionalize(joint_gm, remove="mutations_and_views"),
|
| 344 |
+
fw_args + example_grads,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
return HopJointGraph(
|
| 348 |
+
joint_gm,
|
| 349 |
+
len(fw_args),
|
| 350 |
+
len(fw_gm_output_nodes),
|
| 351 |
+
functionalized=functionalize,
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
class HopGraphMinCutPartitioner:
|
| 356 |
+
@staticmethod
|
| 357 |
+
def create_partitioned_graph(
|
| 358 |
+
fw_fn: Callable,
|
| 359 |
+
fw_args: tuple[torch.Tensor | torch.SymInt, ...],
|
| 360 |
+
*,
|
| 361 |
+
always_recompute_complex_exprs: bool = False,
|
| 362 |
+
) -> HopPartitionedGraph:
|
| 363 |
+
"""
|
| 364 |
+
Inputs:
|
| 365 |
+
- fw_fn: the forward function that we'll use to create a joint graph and partition
|
| 366 |
+
- fw_args: the flat_args to fw_fn
|
| 367 |
+
- always_recompute_complex_exprs: when set to True, the bw_gm will do a re-compute
|
| 368 |
+
for inputs that are complex expressions such that the partitioning boundary
|
| 369 |
+
only consists of basic symbols and tensors.
|
| 370 |
+
|
| 371 |
+
Returns a HopPartitionedGraph
|
| 372 |
+
"""
|
| 373 |
+
from torch._functorch.partitioners import min_cut_rematerialization_partition
|
| 374 |
+
|
| 375 |
+
joint_graph: HopJointGraph = create_hop_joint_graph(
|
| 376 |
+
fw_fn, fw_args, functionalize=True
|
| 377 |
+
)
|
| 378 |
+
return joint_graph.partition(
|
| 379 |
+
min_cut_rematerialization_partition, always_recompute_complex_exprs
|
| 380 |
+
)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/passes/__init__.py
ADDED
|
File without changes
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/passes/inline_invoke_subgraph.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import operator
|
| 2 |
+
from typing import Any, TYPE_CHECKING
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch.fx.graph_module import GraphModule
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from torch.fx.node import Node
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def inline_invoke_subgraph(gm: GraphModule) -> GraphModule:
|
| 13 |
+
"""Inline all invoke_subgraph HOPs, producing a flat FX graph.
|
| 14 |
+
|
| 15 |
+
This is useful when downstream compilers (like vllm-compile) don't support
|
| 16 |
+
HOPs or prefer a flat graph, but we still want the Dynamo tracing-time
|
| 17 |
+
benefits of auto-caching (trace once, stamp out cached calls).
|
| 18 |
+
"""
|
| 19 |
+
invoke_nodes = list(
|
| 20 |
+
gm.graph.find_nodes(
|
| 21 |
+
op="call_function", target=torch.ops.higher_order.invoke_subgraph
|
| 22 |
+
)
|
| 23 |
+
)
|
| 24 |
+
if not invoke_nodes:
|
| 25 |
+
return gm
|
| 26 |
+
|
| 27 |
+
# Recursively inline any nested invoke_subgraph calls inside
|
| 28 |
+
# subgraph modules themselves.
|
| 29 |
+
for name, mod in gm.named_modules():
|
| 30 |
+
if name and isinstance(mod, GraphModule):
|
| 31 |
+
inline_invoke_subgraph(mod)
|
| 32 |
+
|
| 33 |
+
for node in invoke_nodes:
|
| 34 |
+
get_attr_node = node.args[0]
|
| 35 |
+
# args[1] is the identifier string, args[2:] are operands
|
| 36 |
+
operands = node.args[2:]
|
| 37 |
+
|
| 38 |
+
subgraph: GraphModule = getattr(gm, get_attr_node.target)
|
| 39 |
+
|
| 40 |
+
# Build mapping from subgraph placeholder nodes -> parent operands
|
| 41 |
+
env: dict[Node, Any] = dict(
|
| 42 |
+
zip(subgraph.graph.find_nodes(op="placeholder"), operands)
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
# Copy subgraph nodes into parent graph, inserting before the
|
| 46 |
+
# invoke_subgraph node.
|
| 47 |
+
with gm.graph.inserting_before(node):
|
| 48 |
+
for sub_node in subgraph.graph.nodes:
|
| 49 |
+
if sub_node.op in ("placeholder", "output"):
|
| 50 |
+
continue
|
| 51 |
+
env[sub_node] = gm.graph.node_copy(sub_node, lambda n: env[n])
|
| 52 |
+
|
| 53 |
+
output_values = subgraph.graph.output_node().args[0]
|
| 54 |
+
|
| 55 |
+
# Replace getitem users of the invoke_subgraph result with the
|
| 56 |
+
# corresponding inlined output.
|
| 57 |
+
for user in list(node.users):
|
| 58 |
+
if user.op == "call_function" and user.target is operator.getitem:
|
| 59 |
+
idx = user.args[1]
|
| 60 |
+
user.replace_all_uses_with(env[output_values[idx]]) # pyrefly: ignore
|
| 61 |
+
gm.graph.erase_node(user)
|
| 62 |
+
|
| 63 |
+
gm.graph.erase_node(node)
|
| 64 |
+
|
| 65 |
+
# Remove the get_attr node if it has no other users.
|
| 66 |
+
if not get_attr_node.users:
|
| 67 |
+
gm.graph.erase_node(get_attr_node)
|
| 68 |
+
|
| 69 |
+
return gm
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/print.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import builtins
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.utils._pytree as pytree
|
| 5 |
+
from torch._ops import HigherOrderOperator
|
| 6 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 7 |
+
from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Print(HigherOrderOperator):
|
| 11 |
+
"""
|
| 12 |
+
print(format_str, *args, **kwargs) -> None
|
| 13 |
+
|
| 14 |
+
This Higher Order Operator (HOP) provides a functional version of print for use in PyTorch graphs.
|
| 15 |
+
It supports the calling conventions of print(format_str.format(*args, **kwargs)):
|
| 16 |
+
|
| 17 |
+
1. Format string with keyword arguments (named placeholders):
|
| 18 |
+
torch._higher_order_ops.print("moo {x} {y}", x=1, y=2)
|
| 19 |
+
Output: "moo 1 2"
|
| 20 |
+
|
| 21 |
+
2. Format string with positional arguments (positional placeholders):
|
| 22 |
+
torch._higher_order_ops.print("moo {} {}", 1, 2)
|
| 23 |
+
Output: "moo 1 2"
|
| 24 |
+
|
| 25 |
+
3. Mixed positional and keyword arguments:
|
| 26 |
+
torch._higher_order_ops.print("moo {} {y}", 1, y=2)
|
| 27 |
+
Output: "moo 1 2"
|
| 28 |
+
|
| 29 |
+
4. DTensor support:
|
| 30 |
+
DTensor args are unwrapped to local tensors via to_local() (no collective).
|
| 31 |
+
Each rank prints its own local view, prefixed with [rank N].
|
| 32 |
+
For the global view of a sharded tensor, call full_tensor() before
|
| 33 |
+
passing to print.
|
| 34 |
+
|
| 35 |
+
dt = DTensor.from_local(local_shard, mesh, [Shard(0)])
|
| 36 |
+
torch._higher_order_ops.print("activations: {}", dt)
|
| 37 |
+
# Output: [rank 0] activations: tensor([0., 1.])
|
| 38 |
+
|
| 39 |
+
This HOP enables printing without causing graph break.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(self) -> None:
|
| 43 |
+
super().__init__("print")
|
| 44 |
+
|
| 45 |
+
def __call__(self, format_str: str, *args: object, **kwargs: object) -> None:
|
| 46 |
+
if not isinstance(format_str, str):
|
| 47 |
+
raise AssertionError(f"format_str must be a string, got {type(format_str)}")
|
| 48 |
+
# pyrefly: ignore [missing-attribute]
|
| 49 |
+
return super().__call__(format_str, *args, **kwargs)
|
| 50 |
+
|
| 51 |
+
# pyrefly: ignore [bad-override]
|
| 52 |
+
def gen_schema(
|
| 53 |
+
self, format_str: str, *args: object, **kwargs: object
|
| 54 |
+
) -> torch.FunctionSchema:
|
| 55 |
+
from torch._higher_order_ops.schema import HopSchemaGenerator
|
| 56 |
+
|
| 57 |
+
schema_gen = HopSchemaGenerator(self)
|
| 58 |
+
schema_gen.add_arg("format_str", format_str[0])
|
| 59 |
+
|
| 60 |
+
# Add each positional arg
|
| 61 |
+
for i, value in enumerate(args):
|
| 62 |
+
schema_gen.add_arg(f"arg{i}", value)
|
| 63 |
+
|
| 64 |
+
# Add each kwarg as a keyword-only argument
|
| 65 |
+
for key, value in kwargs.items():
|
| 66 |
+
schema_gen.add_arg(key, value, kw_only=True)
|
| 67 |
+
|
| 68 |
+
schema_gen.add_schema_tree_spec(format_str, *args, **kwargs)
|
| 69 |
+
|
| 70 |
+
return schema_gen.gen_schema()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
print = Print()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@print.py_impl(ProxyTorchDispatchMode)
|
| 77 |
+
# pyre-ignore
|
| 78 |
+
def print_proxy_torch_dispatch_mode(
|
| 79 |
+
mode: ProxyTorchDispatchMode, format_str: str, *args: object, **kwargs: object
|
| 80 |
+
) -> None:
|
| 81 |
+
proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args) # type: ignore[union-attr]
|
| 82 |
+
proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) # type: ignore[union-attr]
|
| 83 |
+
mode.tracer.create_proxy(
|
| 84 |
+
"call_function", print, (format_str, *proxy_args), proxy_kwargs
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@print.py_impl(FakeTensorMode)
|
| 89 |
+
# pyre-ignore
|
| 90 |
+
def print_fake_tensor_mode(mode, format_str: str, *args: object, **kwargs: object):
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@print.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd)
|
| 95 |
+
# pyre-ignore
|
| 96 |
+
def print_impl(format_str: str, *args: object, **kwargs: object) -> None:
|
| 97 |
+
# Ensure all immutable_dict/list in args and kwargs are converted to regular dict/list
|
| 98 |
+
map_types: dict[type, type] = {
|
| 99 |
+
torch.fx.immutable_collections.immutable_dict: dict,
|
| 100 |
+
torch.fx.immutable_collections.immutable_list: list,
|
| 101 |
+
}
|
| 102 |
+
new_args, new_kwargs = pytree.tree_map_only(
|
| 103 |
+
tuple(map_types.keys()),
|
| 104 |
+
lambda a: map_types[type(a)](a),
|
| 105 |
+
(args, kwargs),
|
| 106 |
+
lambda a: isinstance(a, tuple(map_types.keys())),
|
| 107 |
+
)
|
| 108 |
+
# Use built-in print to avoid recursion with the HOP print
|
| 109 |
+
builtins.print(format_str.format(*new_args, **new_kwargs))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
print.fallthrough(torch._C.DispatchKey.AutogradCPU)
|
| 113 |
+
print.fallthrough(torch._C.DispatchKey.AutogradCUDA)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _register_dtensor_impl() -> None:
|
| 117 |
+
from torch.distributed.tensor import DTensor
|
| 118 |
+
|
| 119 |
+
@print.py_impl(DTensor) # pyrefly: ignore [missing-attribute]
|
| 120 |
+
# pyre-ignore
|
| 121 |
+
def print_dtensor(format_str: str, *args: object, **kwargs: object) -> None:
|
| 122 |
+
# Unwrap DTensors to local tensors via to_local() — no collective is
|
| 123 |
+
# introduced so there is no OOM or performance risk. Every rank prints
|
| 124 |
+
# its own local view (including Replicate, where to_local() already
|
| 125 |
+
# holds the full tensor).
|
| 126 |
+
#
|
| 127 |
+
# The output is prefixed with [rank N] so users can identify which rank
|
| 128 |
+
# produced each line.
|
| 129 |
+
#
|
| 130 |
+
# If the user needs the global view of a sharded tensor, they can call
|
| 131 |
+
# full_tensor() explicitly before passing it to print.
|
| 132 |
+
import torch.distributed as dist
|
| 133 |
+
|
| 134 |
+
local_args = pytree.tree_map_only(DTensor, DTensor.to_local, args)
|
| 135 |
+
local_kwargs = pytree.tree_map_only(DTensor, DTensor.to_local, kwargs)
|
| 136 |
+
if dist.is_initialized() and dist.get_world_size() > 1:
|
| 137 |
+
format_str = f"[rank {dist.get_rank()}] {format_str}"
|
| 138 |
+
print( # pyrefly: ignore [no-matching-overload]
|
| 139 |
+
format_str, *local_args, **local_kwargs
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@print.py_functionalize_impl
|
| 144 |
+
def print_func(ctx, format_str: str, *args: object, **kwargs: object):
|
| 145 |
+
from torch._higher_order_ops.effects import handle_effects
|
| 146 |
+
|
| 147 |
+
return handle_effects(
|
| 148 |
+
ctx.mode._allow_token_discovery,
|
| 149 |
+
ctx.mode._tokens,
|
| 150 |
+
print, # type: ignore[arg-type]
|
| 151 |
+
(format_str, *args),
|
| 152 |
+
kwargs, # type: ignore[arg-type]
|
| 153 |
+
)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/run_const_graph.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch._C import DispatchKey
|
| 5 |
+
from torch._higher_order_ops.utils import autograd_not_implemented
|
| 6 |
+
from torch._ops import HigherOrderOperator
|
| 7 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from torch._subclasses.functional_tensor import BaseFunctionalizeAPI
|
| 12 |
+
|
| 13 |
+
from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
|
| 14 |
+
from torch.utils import _pytree as pytree
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class RunConstGraph(HigherOrderOperator):
|
| 18 |
+
def __init__(self) -> None:
|
| 19 |
+
super().__init__("run_const_graph")
|
| 20 |
+
|
| 21 |
+
def __call__(self, graph: torch.fx.GraphModule, args: tuple[object, ...]) -> object:
|
| 22 |
+
# pyrefly: ignore [missing-attribute]
|
| 23 |
+
return super().__call__(graph, args)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
run_const_graph = RunConstGraph()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@run_const_graph.py_impl(ProxyTorchDispatchMode)
|
| 30 |
+
def run_const_graph_dispatch_mode(
|
| 31 |
+
mode: ProxyTorchDispatchMode, graph: torch.fx.GraphModule, args: tuple[object, ...]
|
| 32 |
+
) -> object:
|
| 33 |
+
const_gm, weights = graph, args
|
| 34 |
+
p_args = pytree.tree_map(mode.tracer.unwrap_proxy, (graph, args)) # type: ignore[union-attr]
|
| 35 |
+
if not isinstance(const_gm, torch.fx.GraphModule):
|
| 36 |
+
raise AssertionError(
|
| 37 |
+
f"expected const_gm to be torch.fx.GraphModule, got {type(const_gm)}"
|
| 38 |
+
)
|
| 39 |
+
if hasattr(mode.tracer.root, "_const_graph"): # type: ignore[union-attr]
|
| 40 |
+
raise AssertionError("mode.tracer.root already has _const_graph attribute")
|
| 41 |
+
mode.tracer.root.register_module("_const_graph", const_gm) # type: ignore[union-attr]
|
| 42 |
+
|
| 43 |
+
proxy = mode.tracer.create_proxy("call_function", run_const_graph, p_args, {})
|
| 44 |
+
|
| 45 |
+
out = const_gm(*weights)
|
| 46 |
+
return track_tensor_tree(out, proxy, constant=None, tracer=mode.tracer)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@run_const_graph.py_functionalize_impl
|
| 50 |
+
def run_const_graph_functional(
|
| 51 |
+
ctx: "BaseFunctionalizeAPI", graph: torch.fx.GraphModule, args: tuple[Any, ...]
|
| 52 |
+
) -> Any:
|
| 53 |
+
unwrapped_args = ctx.unwrap_tensors(args)
|
| 54 |
+
|
| 55 |
+
with ctx.redispatch_to_next():
|
| 56 |
+
out = run_const_graph(graph, unwrapped_args)
|
| 57 |
+
return ctx.wrap_tensors(out) # type: ignore[arg-type]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
run_const_graph.py_autograd_impl(
|
| 61 |
+
autograd_not_implemented(run_const_graph, deferred_error=True)
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@run_const_graph.py_impl(FakeTensorMode)
|
| 66 |
+
def run_const_graph_fake_tensor_mode(
|
| 67 |
+
mode: FakeTensorMode, graph: torch.fx.GraphModule, args: tuple[object, ...]
|
| 68 |
+
) -> object:
|
| 69 |
+
if not isinstance(graph, torch.fx.GraphModule):
|
| 70 |
+
raise AssertionError(
|
| 71 |
+
f"expected graph to be torch.fx.GraphModule, got {type(graph)}"
|
| 72 |
+
)
|
| 73 |
+
with mode:
|
| 74 |
+
return graph(*args)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@run_const_graph.py_impl(DispatchKey.CPU)
|
| 78 |
+
def run_const_graph_cpu(
|
| 79 |
+
graph: torch.fx.GraphModule, args: tuple[object, ...]
|
| 80 |
+
) -> object:
|
| 81 |
+
if not isinstance(graph, torch.fx.GraphModule):
|
| 82 |
+
raise AssertionError(
|
| 83 |
+
f"expected graph to be torch.fx.GraphModule, got {type(graph)}"
|
| 84 |
+
)
|
| 85 |
+
return graph(*args)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/scan.py
ADDED
|
@@ -0,0 +1,994 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import enum
|
| 3 |
+
import functools
|
| 4 |
+
import itertools
|
| 5 |
+
import logging
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch._prims_common as utils
|
| 11 |
+
import torch.utils._pytree as pytree
|
| 12 |
+
from torch._C import DispatchKey
|
| 13 |
+
from torch._higher_order_ops.partitioner import (
|
| 14 |
+
_find_hop_subgraph_outputs,
|
| 15 |
+
HopGraphMinCutPartitioner,
|
| 16 |
+
HopPartitionedGraph,
|
| 17 |
+
)
|
| 18 |
+
from torch._higher_order_ops.utils import (
|
| 19 |
+
_maybe_compile_and_run_fn,
|
| 20 |
+
check_input_alias_and_mutation_return_outputs,
|
| 21 |
+
check_meta_consistency,
|
| 22 |
+
fill_none_with_masks,
|
| 23 |
+
filter_with_masks,
|
| 24 |
+
first_slice_copy,
|
| 25 |
+
get_tensor_mask,
|
| 26 |
+
mask_list,
|
| 27 |
+
materialize_as_graph,
|
| 28 |
+
reenter_make_fx,
|
| 29 |
+
split_into_chunks,
|
| 30 |
+
unique_graph_id,
|
| 31 |
+
validate_subgraph_args_types,
|
| 32 |
+
)
|
| 33 |
+
from torch._ops import HigherOrderOperator
|
| 34 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 35 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 36 |
+
disable_proxy_modes_tracing,
|
| 37 |
+
ProxyTorchDispatchMode,
|
| 38 |
+
track_tensor_tree,
|
| 39 |
+
)
|
| 40 |
+
from torch.utils._python_dispatch import _get_current_dispatch_mode
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
logger: logging.Logger = logging.getLogger(__name__)
|
| 44 |
+
aten = torch._ops.ops.aten
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def wrap_combine_fn_flat(
|
| 48 |
+
*args, combine_fn, spec_init, spec_xs, num_init_leaves, num_inp_leaves
|
| 49 |
+
):
|
| 50 |
+
if len(args) != (num_init_leaves + num_inp_leaves):
|
| 51 |
+
raise AssertionError(
|
| 52 |
+
f"combine_fn received wrong number of arguments, expected {num_init_leaves + num_inp_leaves}, but got {len(args)}"
|
| 53 |
+
)
|
| 54 |
+
carry = pytree.tree_unflatten(args[:num_init_leaves], spec_init)
|
| 55 |
+
xs = pytree.tree_unflatten(args[num_init_leaves:], spec_xs)
|
| 56 |
+
return combine_fn(carry, xs)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _extract_carry_and_out(flat_out: list[Any], num_carry: int):
|
| 60 |
+
return split_into_chunks(flat_out, [num_carry, len(flat_out) - num_carry])
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# We also do a clone with contiguous_format. This is to be consistent with
|
| 64 |
+
# eager semantic of scan, which stacks the outputs. The result is contiguous
|
| 65 |
+
# as a result of the stack operation.
|
| 66 |
+
def stack_y(y: torch.Tensor, scan_length: int) -> torch.Tensor:
|
| 67 |
+
return (
|
| 68 |
+
y.unsqueeze(0)
|
| 69 |
+
.repeat(*([scan_length] + [1] * y.ndim))
|
| 70 |
+
.clone(memory_format=torch.contiguous_format)
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def call_operator(operator, *args):
|
| 75 |
+
return pytree.tree_leaves(operator(*args))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def scan(
|
| 79 |
+
combine_fn: Callable[
|
| 80 |
+
[pytree.PyTree, pytree.PyTree], tuple[pytree.PyTree, pytree.PyTree]
|
| 81 |
+
],
|
| 82 |
+
init: pytree.PyTree,
|
| 83 |
+
xs: pytree.PyTree,
|
| 84 |
+
*,
|
| 85 |
+
dim: int = 0,
|
| 86 |
+
reverse: bool = False,
|
| 87 |
+
) -> tuple[pytree.PyTree, pytree.PyTree]:
|
| 88 |
+
r"""
|
| 89 |
+
Performs an inclusive scan with a combine function.
|
| 90 |
+
|
| 91 |
+
.. warning::
|
| 92 |
+
|
| 93 |
+
``torch.scan`` is a prototype feature in PyTorch. You may run into miscompiles.
|
| 94 |
+
Read more about feature classification at:
|
| 95 |
+
https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
combine_fn (Callable): A binary callable with type ``(Tensor, Tensor) -> (Tensor, Tensor)``,
|
| 99 |
+
or if xs is a pytree ``(pytree, pytree) -> (pytree, pytree)``.
|
| 100 |
+
The first input to ``combine_fn`` is the previous or initial scan carry
|
| 101 |
+
and the second input element to ``combine_fn`` is a slice of the input along dim.
|
| 102 |
+
The first output element of ``combine_fn`` is the next scan carry
|
| 103 |
+
and the second output of ``combine_fn`` represents a slice of the output.
|
| 104 |
+
This function must be pure, i.e., no lifted arguments are supported at the moment
|
| 105 |
+
and may not have any side effects.
|
| 106 |
+
init (torch.Tensor or pytree with tensor leaves): The initial scan carry, a tensor, or nested pytree of tensors.
|
| 107 |
+
The ``init`` is expected to have the same pytree structure as the first output element (i.e. carry)
|
| 108 |
+
of ``combine_fn``.
|
| 109 |
+
xs (torch.Tensor or pytree with tensor leaves): The input tensor, or nested pytree of tensors.
|
| 110 |
+
|
| 111 |
+
Kwargs:
|
| 112 |
+
dim (int): the dimension to scan over, default 0.
|
| 113 |
+
reverse (bool): A boolean stating if the scan should be reversed with respect to ``dim``, default ``False``.
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
final_carry (torch.Tensor or pytree with tensor leaves),
|
| 117 |
+
the final carry of the scan operation with same pytree structure as init.
|
| 118 |
+
out (torch.Tensor or pytree with tensor leaves),
|
| 119 |
+
each tensor leaf is a stacked output along first dim, where each slice is the output of a scan iteration.
|
| 120 |
+
|
| 121 |
+
Restrictions:
|
| 122 |
+
- The combine_fn shouldn't have any aliasing between input-input, input-output, and output-output. E.g. return a view
|
| 123 |
+
or the same tensor as input is not supported. As a workaround, can clone the output to avoid aliasing.
|
| 124 |
+
|
| 125 |
+
- The combine_fn shouldn't mutate any inputs. We'll remove the mutation restriction for inference soon. Please file an issue
|
| 126 |
+
if you input mutation support for training is needed.
|
| 127 |
+
|
| 128 |
+
- The combine_fn's init carry should match the next_carry in pytree structure and in tensor metadata.
|
| 129 |
+
|
| 130 |
+
Example::
|
| 131 |
+
|
| 132 |
+
def add(x: torch.Tensor, y: torch.Tensor):
|
| 133 |
+
next_carry = y = x + y
|
| 134 |
+
# clone the output to avoid output-output aliasing
|
| 135 |
+
return next_carry, y.clone()
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
i0 = torch.zeros(1)
|
| 139 |
+
xs = torch.arange(5)
|
| 140 |
+
# returns torch.tensor([10.]), torch.tensor([[0], [1.], [3.], [6.], [10.]])
|
| 141 |
+
last_carry, cumsum = scan(add, init=i0, xs=xs)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
"""
|
| 145 |
+
# The reason we flatten init and xs before calling into dynamo is that
|
| 146 |
+
# we want to create a consistent input ordering for combine_fn
|
| 147 |
+
# and we also want to the input ordering matches the output ordering.
|
| 148 |
+
leaves_init, spec_init = pytree.tree_flatten(init)
|
| 149 |
+
leaves_xs_orig, spec_xs = pytree.tree_flatten(xs)
|
| 150 |
+
|
| 151 |
+
# Shortcut if no xs is provided
|
| 152 |
+
if len(leaves_xs_orig) == 0:
|
| 153 |
+
return init, []
|
| 154 |
+
|
| 155 |
+
def _validate_input(cfn, lxs, linit, d, r):
|
| 156 |
+
# Basic arguments check
|
| 157 |
+
if not callable(cfn):
|
| 158 |
+
raise RuntimeError(f"Combine_fn must be a callable, but got {cfn}")
|
| 159 |
+
if not isinstance(d, int):
|
| 160 |
+
raise RuntimeError("Dim must be an int, but got " + str(type(d)))
|
| 161 |
+
if not isinstance(r, bool):
|
| 162 |
+
raise RuntimeError("Reverse must be a bool, but got " + str(type(r)))
|
| 163 |
+
|
| 164 |
+
# Checks for init
|
| 165 |
+
if len(linit) == 0:
|
| 166 |
+
raise RuntimeError("scan() operator requires init leaves.")
|
| 167 |
+
for x in linit:
|
| 168 |
+
if not isinstance(x, torch.Tensor):
|
| 169 |
+
raise RuntimeError(f"All init leaves must be a Tensor but got {x}")
|
| 170 |
+
|
| 171 |
+
# Checks for xs
|
| 172 |
+
for x in lxs:
|
| 173 |
+
if not isinstance(x, torch.Tensor):
|
| 174 |
+
raise RuntimeError(f"All xs leaves must be a Tensor but got {x}")
|
| 175 |
+
if any(x.ndim <= d for x in lxs):
|
| 176 |
+
raise RuntimeError(
|
| 177 |
+
"All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0"
|
| 178 |
+
)
|
| 179 |
+
if any(x.shape[d] == 0 for x in lxs):
|
| 180 |
+
raise RuntimeError(
|
| 181 |
+
"All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0"
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
ndim = leaves_xs_orig[0].ndim
|
| 185 |
+
dim = utils.canonicalize_dim(ndim, dim)
|
| 186 |
+
|
| 187 |
+
_validate_input(combine_fn, leaves_xs_orig, leaves_init, dim, reverse)
|
| 188 |
+
|
| 189 |
+
# Move scan dim to 0 and always perform scan on dim 0
|
| 190 |
+
leaves_xs = []
|
| 191 |
+
for elem in leaves_xs_orig:
|
| 192 |
+
leaves_xs.append(torch.movedim(elem, dim, 0) if dim != 0 else elem)
|
| 193 |
+
|
| 194 |
+
if reverse:
|
| 195 |
+
leaves_xs = [torch.flip(elem, [0]) for elem in leaves_xs]
|
| 196 |
+
|
| 197 |
+
# TODO: Support _inductor lowering
|
| 198 |
+
# TODO: Unify handling of pytrees for control flow ops, such as cond, while_loop, etc.
|
| 199 |
+
|
| 200 |
+
combine_fn = functools.partial(
|
| 201 |
+
wrap_combine_fn_flat,
|
| 202 |
+
combine_fn=combine_fn,
|
| 203 |
+
spec_init=spec_init,
|
| 204 |
+
spec_xs=spec_xs,
|
| 205 |
+
num_init_leaves=len(leaves_init),
|
| 206 |
+
num_inp_leaves=len(leaves_xs),
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
def run_flattened_scan(combine_fn, leaves_init, leaves_xs):
|
| 210 |
+
return scan_op(combine_fn, leaves_init, leaves_xs, additional_inputs=())
|
| 211 |
+
|
| 212 |
+
carry, out = _maybe_compile_and_run_fn(
|
| 213 |
+
run_flattened_scan,
|
| 214 |
+
combine_fn,
|
| 215 |
+
leaves_init,
|
| 216 |
+
leaves_xs,
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
if reverse:
|
| 220 |
+
out = pytree.tree_map(lambda elem: elem.flip([0]), out)
|
| 221 |
+
|
| 222 |
+
return carry, out
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class ScanOp(HigherOrderOperator):
|
| 226 |
+
def __init__(self):
|
| 227 |
+
super().__init__("scan")
|
| 228 |
+
|
| 229 |
+
def __call__(self, combine_fn, init, xs, additional_inputs):
|
| 230 |
+
# There is currently an issue that the ScanOp is sometimes called with
|
| 231 |
+
# the additional_inputs being a list. See https://github.com/pytorch/pytorch/issues/145785
|
| 232 |
+
# Once this issue is resolved, the assertion should only allow tuples
|
| 233 |
+
# and the tuple cast should be removed
|
| 234 |
+
if not isinstance(additional_inputs, (tuple, list)):
|
| 235 |
+
raise AssertionError(
|
| 236 |
+
f"additional_inputs must be a tuple or list, got {type(additional_inputs)}"
|
| 237 |
+
)
|
| 238 |
+
additional_inputs = (
|
| 239 |
+
tuple(additional_inputs)
|
| 240 |
+
if isinstance(additional_inputs, list)
|
| 241 |
+
else additional_inputs
|
| 242 |
+
)
|
| 243 |
+
validate_subgraph_args_types(additional_inputs)
|
| 244 |
+
# pyrefly: ignore [missing-attribute]
|
| 245 |
+
return super().__call__(combine_fn, init, xs, additional_inputs)
|
| 246 |
+
|
| 247 |
+
# pyrefly: ignore [bad-override]
|
| 248 |
+
def gen_schema(self, combine_fn, init, xs, additional_inputs):
|
| 249 |
+
from torch._higher_order_ops.schema import HopSchemaGenerator
|
| 250 |
+
from torch._higher_order_ops.utils import materialize_as_graph
|
| 251 |
+
|
| 252 |
+
all_inputs = tuple(
|
| 253 |
+
list(init) + [first_slice_copy(x) for x in xs] + list(additional_inputs)
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
combine_gm: torch.fx.GraphModule = materialize_as_graph(combine_fn, all_inputs)
|
| 257 |
+
|
| 258 |
+
(
|
| 259 |
+
_,
|
| 260 |
+
_,
|
| 261 |
+
_,
|
| 262 |
+
mutated_inputs,
|
| 263 |
+
outputs,
|
| 264 |
+
) = check_input_alias_and_mutation_return_outputs(combine_gm)
|
| 265 |
+
if len(mutated_inputs) > 0:
|
| 266 |
+
raise RuntimeError(
|
| 267 |
+
"For scan, combine_fn cannot have in-place mutations but found "
|
| 268 |
+
f"{mutated_inputs}-th inputs are mutated."
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
schema_gen = HopSchemaGenerator(self)
|
| 272 |
+
schema_gen.add_arg("combine_fn", combine_gm)
|
| 273 |
+
|
| 274 |
+
for idx, arg in enumerate(init):
|
| 275 |
+
schema_gen.add_arg(f"init{idx}", arg)
|
| 276 |
+
|
| 277 |
+
for idx, arg in enumerate(xs):
|
| 278 |
+
schema_gen.add_arg(f"xs{idx}", arg)
|
| 279 |
+
|
| 280 |
+
for idx, arg in enumerate(additional_inputs):
|
| 281 |
+
schema_gen.add_arg(f"additional_input{idx}", arg)
|
| 282 |
+
|
| 283 |
+
for out in outputs:
|
| 284 |
+
schema_gen.add_output(out)
|
| 285 |
+
|
| 286 |
+
schema_gen.add_schema_tree_spec(combine_fn, init, xs, additional_inputs)
|
| 287 |
+
return schema_gen.gen_schema()
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
scan_op = ScanOp()
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def generic_scan(operator, init, xs, dim=0, additional_inputs=()):
|
| 294 |
+
def _scan(init, xs):
|
| 295 |
+
"""Perform scan on `elems` using `elems_init."""
|
| 296 |
+
carry = init
|
| 297 |
+
if len(xs) == 0:
|
| 298 |
+
return carry, []
|
| 299 |
+
|
| 300 |
+
num_elems = xs[0].shape[dim]
|
| 301 |
+
num_init_leaves = len(init)
|
| 302 |
+
|
| 303 |
+
# Process element 0 to infer output shapes for pre-allocation
|
| 304 |
+
# AND produce the first real result in a single call. The previous
|
| 305 |
+
# approach used first_slice_copy() for shape inference and then
|
| 306 |
+
# re-processed element 0 in the main loop, calling the operator
|
| 307 |
+
# num_elems+1 times. That extra invocation is incorrect for
|
| 308 |
+
# operators with side effects.
|
| 309 |
+
carry, out_0 = _extract_carry_and_out(
|
| 310 |
+
call_operator(
|
| 311 |
+
operator,
|
| 312 |
+
*carry,
|
| 313 |
+
*[elem.select(dim, 0) for elem in xs],
|
| 314 |
+
*additional_inputs,
|
| 315 |
+
),
|
| 316 |
+
num_init_leaves,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
out_tensor_mask = get_tensor_mask(out_0)
|
| 320 |
+
out_0_masked = mask_list(out_tensor_mask, out_0)
|
| 321 |
+
|
| 322 |
+
# Pre-allocate
|
| 323 |
+
# outs -> Output matrix
|
| 324 |
+
# idxs -> Index matrix for scatter_
|
| 325 |
+
# out: (num_elems, M, N, ...)
|
| 326 |
+
# idx: (1, M, N)
|
| 327 |
+
outs = [
|
| 328 |
+
torch.empty(
|
| 329 |
+
[num_elems] + list(e.size()),
|
| 330 |
+
dtype=e.dtype,
|
| 331 |
+
device=e.device,
|
| 332 |
+
)
|
| 333 |
+
for e in out_0_masked
|
| 334 |
+
]
|
| 335 |
+
idxs = [
|
| 336 |
+
torch.ones_like(e, dtype=torch.int64).unsqueeze(0) for e in out_0_masked
|
| 337 |
+
]
|
| 338 |
+
|
| 339 |
+
def store_out_in_outs(out, ind):
|
| 340 |
+
# Store the intermediate out in the outs matrix
|
| 341 |
+
for o, x, idx in zip(outs, out, idxs):
|
| 342 |
+
# o: (num_elems, M, N ...)
|
| 343 |
+
# x: (M, N, ...) -> (1, M, N)
|
| 344 |
+
# ind * idx: (1, M, N,) with values to be ind
|
| 345 |
+
# essentially: o[ind][n][k] = x[0][n][k]
|
| 346 |
+
o.scatter_(0, ind * idx, x.unsqueeze(0))
|
| 347 |
+
|
| 348 |
+
# Store element 0's result, then continue from element 1.
|
| 349 |
+
store_out_in_outs(out_0_masked, 0)
|
| 350 |
+
|
| 351 |
+
for i in range(1, num_elems):
|
| 352 |
+
carry, out = _extract_carry_and_out(
|
| 353 |
+
call_operator(
|
| 354 |
+
operator,
|
| 355 |
+
*carry,
|
| 356 |
+
*[elem.select(dim, i) for elem in xs],
|
| 357 |
+
*additional_inputs,
|
| 358 |
+
),
|
| 359 |
+
num_init_leaves,
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
store_out_in_outs(mask_list(out_tensor_mask, out), i)
|
| 363 |
+
|
| 364 |
+
# Expand outs with None depending on the tensor mask of the output
|
| 365 |
+
outs_expanded = [outs.pop(0) if out_m else None for out_m in out_tensor_mask]
|
| 366 |
+
|
| 367 |
+
return (*carry, *outs_expanded)
|
| 368 |
+
|
| 369 |
+
scans = _scan(init, xs)
|
| 370 |
+
return scans
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def trace_scan(
|
| 374 |
+
proxy_mode,
|
| 375 |
+
func_overload,
|
| 376 |
+
combine_fn: Callable,
|
| 377 |
+
init: list[torch.Tensor],
|
| 378 |
+
xs: list[torch.Tensor],
|
| 379 |
+
additional_inputs: tuple[torch.Tensor],
|
| 380 |
+
):
|
| 381 |
+
from torch._dynamo.utils import clone_input
|
| 382 |
+
|
| 383 |
+
with disable_proxy_modes_tracing():
|
| 384 |
+
sample_inits = [clone_input(x_init) for x_init in init]
|
| 385 |
+
sample_inputs = [first_slice_copy(x) for x in xs]
|
| 386 |
+
sample_additional_inputs = [
|
| 387 |
+
clone_input(x) if isinstance(x, torch.Tensor) else x
|
| 388 |
+
for x in additional_inputs
|
| 389 |
+
]
|
| 390 |
+
combine_graph = reenter_make_fx(combine_fn)(
|
| 391 |
+
*sample_inits, *sample_inputs, *sample_additional_inputs
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
outputs = None
|
| 395 |
+
for node in combine_graph.graph.nodes:
|
| 396 |
+
if node.op == "output":
|
| 397 |
+
if outputs is not None:
|
| 398 |
+
raise AssertionError("found multiple output nodes in combine_graph")
|
| 399 |
+
if len(node.args) != 1:
|
| 400 |
+
raise AssertionError(
|
| 401 |
+
f"expected output node to have 1 arg, got {len(node.args)}"
|
| 402 |
+
)
|
| 403 |
+
outputs = node.args[0]
|
| 404 |
+
|
| 405 |
+
if outputs is None:
|
| 406 |
+
raise AssertionError("no output node found in combine_graph")
|
| 407 |
+
|
| 408 |
+
carry, output = _extract_carry_and_out(outputs, len(init))
|
| 409 |
+
init_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [
|
| 410 |
+
i.clone() for i in init
|
| 411 |
+
]
|
| 412 |
+
carry_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [
|
| 413 |
+
c.meta["val"] for c in carry
|
| 414 |
+
]
|
| 415 |
+
check_meta_consistency(
|
| 416 |
+
init_fake_tensors, carry_fake_tensors, "init", "carry", include_contiguity=False
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
_, combine_graph_name = unique_graph_id(proxy_mode, prefix="scan_combine_graph")
|
| 420 |
+
|
| 421 |
+
proxy_mode.tracer.root.register_module(combine_graph_name, combine_graph)
|
| 422 |
+
|
| 423 |
+
args = (combine_graph, init, xs, additional_inputs)
|
| 424 |
+
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args)
|
| 425 |
+
out_proxy = proxy_mode.tracer.create_proxy(
|
| 426 |
+
"call_function", func_overload, proxy_args, {}, name="scan"
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
with disable_proxy_modes_tracing():
|
| 430 |
+
scan_length = xs[0].shape[0]
|
| 431 |
+
fake_carry, fake_outputs = _extract_carry_and_out(
|
| 432 |
+
[o.meta["val"] for o in outputs], len(init)
|
| 433 |
+
)
|
| 434 |
+
out = (
|
| 435 |
+
*fake_carry,
|
| 436 |
+
*(stack_y(t, scan_length) for t in fake_outputs),
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
@scan_op.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 443 |
+
def scan_op_dense(combine_fn, init, xs, additional_inputs):
|
| 444 |
+
mode = _get_current_dispatch_mode()
|
| 445 |
+
if mode is not None:
|
| 446 |
+
raise AssertionError("Mode should never be enabled for CPU/CUDA key")
|
| 447 |
+
return generic_scan(combine_fn, init, xs, additional_inputs=additional_inputs)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
class ScanAutogradOp(torch.autograd.Function):
|
| 451 |
+
"""
|
| 452 |
+
NOTE: [scan partial grad handling]
|
| 453 |
+
If any element of init, of xs, of the outputs or of the additional_inputs does not require gradients,
|
| 454 |
+
i.e., requires_grad=False, there will be still gradients returned for those elements,
|
| 455 |
+
but those gradients will be a tensor filled with zeros of the same shape as the element itself.
|
| 456 |
+
|
| 457 |
+
A special case are additional_inputs that are not tensors. Such inputs can occur for example with symbolic tracing,
|
| 458 |
+
where the shape symbol (SymInt) becomes an additional_input.
|
| 459 |
+
For such cases, we compute a ``additional_inputs_tensor_mask``, which is True for elements of additional_inputs
|
| 460 |
+
that are tensors and False otherwise. Gradients of additional_inputs are only accumulated if this mask is True,
|
| 461 |
+
otherwise, the value of initial_g_additional_inputs is passed, which is None for non-Tensor values.
|
| 462 |
+
"""
|
| 463 |
+
|
| 464 |
+
@staticmethod
|
| 465 |
+
# pyrefly: ignore [bad-override]
|
| 466 |
+
def forward(
|
| 467 |
+
ctx,
|
| 468 |
+
hop_partitioned_graph,
|
| 469 |
+
n_init,
|
| 470 |
+
n_xs,
|
| 471 |
+
n_additional_inputs,
|
| 472 |
+
*operands,
|
| 473 |
+
):
|
| 474 |
+
init, xs, additional_inputs = split_into_chunks(
|
| 475 |
+
operands, [n_init, n_xs, n_additional_inputs]
|
| 476 |
+
)
|
| 477 |
+
ctx._scan_impl = ScanAutogradImpl(
|
| 478 |
+
hop_partitioned_graph, init, xs, additional_inputs
|
| 479 |
+
)
|
| 480 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 481 |
+
return ctx._scan_impl.call_forward()
|
| 482 |
+
|
| 483 |
+
@staticmethod
|
| 484 |
+
def backward(ctx, *grad_fw_outputs):
|
| 485 |
+
return (
|
| 486 |
+
None,
|
| 487 |
+
None,
|
| 488 |
+
None,
|
| 489 |
+
None,
|
| 490 |
+
*ctx._scan_impl.call_backward(*grad_fw_outputs),
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
class ScanForwardIntermediatesHandlingPolicy(enum.Enum):
|
| 495 |
+
"""
|
| 496 |
+
Partitioner can add interemdiates to the output of original graph.
|
| 497 |
+
These intermediates fall into 4 categories and we want to have different policies for handling them by
|
| 498 |
+
modifying the graph:
|
| 499 |
+
|
| 500 |
+
CLONE: we clone the intermediate when it is a carried input (i.e. init). In this case, this carry will be
|
| 501 |
+
replaced with new values at each forward step so we need to clone the carry as part of return (i.e. ys)
|
| 502 |
+
so as to remove the aliasing and that each step's intermediate will be stacked together and saved in bacwkard.
|
| 503 |
+
|
| 504 |
+
REMOVE_XS: we remove the intermediate from output when it is part of xs. Since xs is read-only, in this case,
|
| 505 |
+
we can directly save them for backward to use.
|
| 506 |
+
|
| 507 |
+
REMOVE_ADDITIONAL_INPUTS: we remove the intermediate from output when it is part of additinonal_inputs. additional_inputs
|
| 508 |
+
are also read-only in each step, we can directly save them for bacwkard to use. We differentiate XS and ADDITIONAL_INPUTS
|
| 509 |
+
so that we could have different treatment for them in backward. In backward, we need to put xs intermediates in carry but
|
| 510 |
+
put additional_inputs as backward scan's additional_inputs.
|
| 511 |
+
|
| 512 |
+
KEEP: this corresponds to a real intermediate tensor operations' output. It varies at each forward step, we could just keep
|
| 513 |
+
it as part of ys.
|
| 514 |
+
|
| 515 |
+
"""
|
| 516 |
+
|
| 517 |
+
KEEP = 0
|
| 518 |
+
CLONE = 1
|
| 519 |
+
REMOVE_XS = 2
|
| 520 |
+
REMOVE_ADDITIONAL_INPUTS = 3
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class ScanAutogradImpl:
|
| 524 |
+
"""
|
| 525 |
+
Wraps over partitioned graph and encapsulates scan-specific implementation details
|
| 526 |
+
"""
|
| 527 |
+
|
| 528 |
+
def __init__(
|
| 529 |
+
self, hop_partitioned_graph: HopPartitionedGraph, init, xs, additional_inputs
|
| 530 |
+
):
|
| 531 |
+
self.hop_partitioned_graph = hop_partitioned_graph
|
| 532 |
+
self.init = init
|
| 533 |
+
self.xs = xs
|
| 534 |
+
self.additional_inputs = additional_inputs
|
| 535 |
+
self.forward_intermediates_handling_policies: list[
|
| 536 |
+
ScanForwardIntermediatesHandlingPolicy
|
| 537 |
+
] = []
|
| 538 |
+
self.saved_fw_xs: list[Any] = []
|
| 539 |
+
self.saved_fw_additional_inputs: list[Any] = []
|
| 540 |
+
self.saved_intermediates: list[Any] = []
|
| 541 |
+
self.fw_spec = pytree.tree_flatten((init, xs, additional_inputs))[1]
|
| 542 |
+
self._optimize_forward_intermediates()
|
| 543 |
+
|
| 544 |
+
def _insert_clone(
|
| 545 |
+
self, need_copy_node: torch.fx.Node, output_node: torch.fx.Node
|
| 546 |
+
) -> torch.fx.Node:
|
| 547 |
+
graph: torch.fx.Graph = output_node.graph
|
| 548 |
+
with graph.inserting_before(output_node):
|
| 549 |
+
clone_node = graph.call_function(
|
| 550 |
+
torch.ops.aten.clone.default,
|
| 551 |
+
args=(need_copy_node,),
|
| 552 |
+
)
|
| 553 |
+
clone_node.meta = (
|
| 554 |
+
need_copy_node.meta.copy() if hasattr(need_copy_node, "meta") else {}
|
| 555 |
+
)
|
| 556 |
+
return clone_node
|
| 557 |
+
|
| 558 |
+
def _optimize_forward_intermediates(self):
|
| 559 |
+
"""
|
| 560 |
+
We optimize the forward intermediates by categorize forward intermediates into categories
|
| 561 |
+
and construct a ScanForwardIntermediatesHandlingPolicy for them
|
| 562 |
+
|
| 563 |
+
"""
|
| 564 |
+
if logger.isEnabledFor(logging.DEBUG):
|
| 565 |
+
logger.debug(
|
| 566 |
+
"Need remove aliasing in fw_gm:\n%s",
|
| 567 |
+
self.hop_partitioned_graph.fw_gm.print_readable(print_output=False),
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
fw_gm = self.hop_partitioned_graph.fw_gm
|
| 571 |
+
fw_all_outputs = _find_hop_subgraph_outputs(fw_gm)
|
| 572 |
+
phs = list(fw_gm.graph.find_nodes(op="placeholder"))
|
| 573 |
+
fw_outputs = fw_all_outputs[: self.hop_partitioned_graph.n_fw_outputs]
|
| 574 |
+
fw_intermediates = fw_all_outputs[self.hop_partitioned_graph.n_fw_outputs :]
|
| 575 |
+
|
| 576 |
+
init_phs, xs_phs, additional_inputs_phs = pytree.tree_unflatten(
|
| 577 |
+
phs, self.fw_spec
|
| 578 |
+
)
|
| 579 |
+
init_node_set, xs_node_set, addi_node_set = (
|
| 580 |
+
set(init_phs),
|
| 581 |
+
set(xs_phs),
|
| 582 |
+
set(additional_inputs_phs),
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
if len(self.forward_intermediates_handling_policies) != 0:
|
| 586 |
+
raise AssertionError(
|
| 587 |
+
"forward_intermediates_handling_policies should be empty"
|
| 588 |
+
)
|
| 589 |
+
if len(self.saved_fw_xs) != 0:
|
| 590 |
+
raise AssertionError("saved_fw_xs should be empty")
|
| 591 |
+
if len(self.saved_fw_additional_inputs) != 0:
|
| 592 |
+
raise AssertionError("saved_fw_additional_inputs should be empty")
|
| 593 |
+
intermediate_idx_to_ph_idx = {}
|
| 594 |
+
ph_idx = {ph: i for i, ph in enumerate(phs)}
|
| 595 |
+
for i, out in enumerate(fw_intermediates):
|
| 596 |
+
if out in init_node_set:
|
| 597 |
+
self.forward_intermediates_handling_policies.append(
|
| 598 |
+
ScanForwardIntermediatesHandlingPolicy.CLONE
|
| 599 |
+
)
|
| 600 |
+
intermediate_idx_to_ph_idx[i] = ph_idx[out]
|
| 601 |
+
elif out in xs_node_set:
|
| 602 |
+
self.forward_intermediates_handling_policies.append(
|
| 603 |
+
ScanForwardIntermediatesHandlingPolicy.REMOVE_XS
|
| 604 |
+
)
|
| 605 |
+
intermediate_idx_to_ph_idx[i] = ph_idx[out]
|
| 606 |
+
elif out in addi_node_set:
|
| 607 |
+
self.forward_intermediates_handling_policies.append(
|
| 608 |
+
ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS
|
| 609 |
+
)
|
| 610 |
+
intermediate_idx_to_ph_idx[i] = ph_idx[out]
|
| 611 |
+
else:
|
| 612 |
+
self.forward_intermediates_handling_policies.append(
|
| 613 |
+
ScanForwardIntermediatesHandlingPolicy.KEEP
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
new_output_node = []
|
| 617 |
+
real_graph_inputs = (
|
| 618 |
+
list(self.init) + list(self.xs) + list(self.additional_inputs)
|
| 619 |
+
)
|
| 620 |
+
fw_output_node = next(iter(fw_gm.graph.find_nodes(op="output")))
|
| 621 |
+
for intermediate_idx, (node, policy) in enumerate(
|
| 622 |
+
zip(fw_intermediates, self.forward_intermediates_handling_policies)
|
| 623 |
+
):
|
| 624 |
+
if policy == ScanForwardIntermediatesHandlingPolicy.CLONE:
|
| 625 |
+
new_output_node.append(self._insert_clone(node, fw_output_node))
|
| 626 |
+
elif policy == ScanForwardIntermediatesHandlingPolicy.REMOVE_XS:
|
| 627 |
+
if intermediate_idx not in intermediate_idx_to_ph_idx:
|
| 628 |
+
raise AssertionError(
|
| 629 |
+
f"intermediate_idx {intermediate_idx} not in intermediate_idx_to_ph_idx"
|
| 630 |
+
)
|
| 631 |
+
inp_idx = intermediate_idx_to_ph_idx[intermediate_idx]
|
| 632 |
+
self.saved_fw_xs.append(real_graph_inputs[inp_idx])
|
| 633 |
+
elif (
|
| 634 |
+
policy
|
| 635 |
+
== ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS
|
| 636 |
+
):
|
| 637 |
+
if intermediate_idx not in intermediate_idx_to_ph_idx:
|
| 638 |
+
raise AssertionError(
|
| 639 |
+
f"intermediate_idx {intermediate_idx} not in intermediate_idx_to_ph_idx for REMOVE_ADDITIONAL_INPUTS"
|
| 640 |
+
)
|
| 641 |
+
inp_idx = intermediate_idx_to_ph_idx[intermediate_idx]
|
| 642 |
+
self.saved_fw_additional_inputs.append(real_graph_inputs[inp_idx])
|
| 643 |
+
else:
|
| 644 |
+
new_output_node.append(node)
|
| 645 |
+
|
| 646 |
+
fw_output_node.args = (tuple(fw_outputs) + tuple(new_output_node),)
|
| 647 |
+
fw_gm.graph.lint()
|
| 648 |
+
fw_gm.recompile()
|
| 649 |
+
|
| 650 |
+
if logger.isEnabledFor(logging.DEBUG):
|
| 651 |
+
logger.debug(
|
| 652 |
+
"after removing aliasing:\n%s", fw_gm.print_readable(print_output=False)
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
def call_forward(self):
|
| 656 |
+
fw_outputs_and_intermediates: tuple[Any] = scan_op(
|
| 657 |
+
self.hop_partitioned_graph.fw_gm, self.init, self.xs, self.additional_inputs
|
| 658 |
+
) # type: ignore[return-type]
|
| 659 |
+
fw_outs = fw_outputs_and_intermediates[
|
| 660 |
+
: self.hop_partitioned_graph.n_fw_outputs
|
| 661 |
+
]
|
| 662 |
+
saved_intermediates = fw_outputs_and_intermediates[
|
| 663 |
+
self.hop_partitioned_graph.n_fw_outputs :
|
| 664 |
+
]
|
| 665 |
+
if len(self.saved_intermediates) != 0:
|
| 666 |
+
raise AssertionError(
|
| 667 |
+
"saved_intermediates should be empty before call_forward"
|
| 668 |
+
)
|
| 669 |
+
self.saved_intermediates.extend(saved_intermediates)
|
| 670 |
+
return tuple(fw_outs)
|
| 671 |
+
|
| 672 |
+
def call_backward(self, *grad_fw_outputs):
|
| 673 |
+
"""
|
| 674 |
+
Recall that fw_outputs = (*carry, *ys), bw_gm takes in (*fw_intermediates, *grad_carry, *grad_ys)
|
| 675 |
+
and returns (*grad_init, *grad_xs, *grad_additional_inputs)
|
| 676 |
+
The bacwkard is a reversed scan that can be constructed as follows:
|
| 677 |
+
|
| 678 |
+
grad_additonal_inputs = torch.zeros_like(additional_inputs)
|
| 679 |
+
bw_init = (grad_carry, grad_additional_inputs)
|
| 680 |
+
bw_xs = (fw_intermediates, grad_ys)
|
| 681 |
+
grad_init, grad_additional_inputs, grad_xs = scan(
|
| 682 |
+
combine_fn,
|
| 683 |
+
bw_init,
|
| 684 |
+
bw_xs,
|
| 685 |
+
reverse = True
|
| 686 |
+
)
|
| 687 |
+
, where combine_fn is defined as follows:
|
| 688 |
+
|
| 689 |
+
def combine_fn(bw_init, bw_xs):
|
| 690 |
+
grad_carry, grad_additional_inputs = bw_init
|
| 691 |
+
fw_intermediates, grad_y = bw_xs
|
| 692 |
+
nxt_grad_carry, grad_x, nxt_grad_additional_inputs = bw_gm(*fw_intermediates, *grad_carry, *grad_y)
|
| 693 |
+
return (nxt_grad_carry, grad_additional_inputs + nxt_grad_additional_inputs), grad_x
|
| 694 |
+
|
| 695 |
+
Note that grad_additional_inputs is accumulated with add, grad_carry is carried over to next iteration and
|
| 696 |
+
grad_x is the ys output, which will be stacked together after the loop and will have the same shape as xs.
|
| 697 |
+
"""
|
| 698 |
+
fw_policy = self.forward_intermediates_handling_policies
|
| 699 |
+
saved_intermediates = self.saved_intermediates
|
| 700 |
+
saved_fw_xs = self.saved_fw_xs
|
| 701 |
+
saved_fw_additional_inputs = self.saved_fw_additional_inputs
|
| 702 |
+
|
| 703 |
+
n_carry = len(self.init)
|
| 704 |
+
|
| 705 |
+
grad_carry, grad_ys = grad_fw_outputs[:n_carry], grad_fw_outputs[n_carry:]
|
| 706 |
+
additional_inputs_tensor_masks = [
|
| 707 |
+
bool(isinstance(t, torch.Tensor)) for t in self.additional_inputs
|
| 708 |
+
]
|
| 709 |
+
grad_additional_inputs = [
|
| 710 |
+
torch.zeros_like(t)
|
| 711 |
+
for t in filter_with_masks(
|
| 712 |
+
self.additional_inputs, additional_inputs_tensor_masks
|
| 713 |
+
)
|
| 714 |
+
]
|
| 715 |
+
|
| 716 |
+
bw_init = [grad_carry, grad_additional_inputs]
|
| 717 |
+
bw_xs = [
|
| 718 |
+
grad_ys,
|
| 719 |
+
saved_fw_xs,
|
| 720 |
+
saved_intermediates,
|
| 721 |
+
]
|
| 722 |
+
bw_additional_inputs = saved_fw_additional_inputs
|
| 723 |
+
|
| 724 |
+
_, flat_spec = pytree.tree_flatten((bw_init, bw_xs, bw_additional_inputs))
|
| 725 |
+
|
| 726 |
+
grad_spec = None
|
| 727 |
+
|
| 728 |
+
def bw_single_step_wrapper(*args):
|
| 729 |
+
bw_init, bw_xs, bw_additional_inputs = pytree.tree_unflatten(
|
| 730 |
+
args, flat_spec
|
| 731 |
+
)
|
| 732 |
+
grad_carry, grad_additional_inputs = bw_init
|
| 733 |
+
grad_y, saved_fw_xs, saved_intermediates = bw_xs
|
| 734 |
+
saved_fw_additional_inputs = bw_additional_inputs
|
| 735 |
+
|
| 736 |
+
fw_intermediates = []
|
| 737 |
+
xs_it = iter(saved_fw_xs)
|
| 738 |
+
carry_it = iter(saved_intermediates)
|
| 739 |
+
addi_it = iter(saved_fw_additional_inputs)
|
| 740 |
+
for policy in fw_policy:
|
| 741 |
+
if policy in (
|
| 742 |
+
ScanForwardIntermediatesHandlingPolicy.CLONE,
|
| 743 |
+
ScanForwardIntermediatesHandlingPolicy.KEEP,
|
| 744 |
+
):
|
| 745 |
+
fw_intermediates.append(next(carry_it))
|
| 746 |
+
elif policy == ScanForwardIntermediatesHandlingPolicy.REMOVE_XS:
|
| 747 |
+
fw_intermediates.append(next(xs_it))
|
| 748 |
+
elif (
|
| 749 |
+
policy
|
| 750 |
+
== ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS
|
| 751 |
+
):
|
| 752 |
+
fw_intermediates.append(next(addi_it))
|
| 753 |
+
else:
|
| 754 |
+
raise RuntimeError(f"Unknown policy: {policy}")
|
| 755 |
+
|
| 756 |
+
grad_fw_outputs = (*grad_carry, *grad_y)
|
| 757 |
+
|
| 758 |
+
flat_out = self.hop_partitioned_graph.bw_gm(
|
| 759 |
+
*fw_intermediates,
|
| 760 |
+
*grad_fw_outputs,
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
next_grad_carry, grad_xs, grad_addi = split_into_chunks(
|
| 764 |
+
flat_out, # type: ignore[arg-type]
|
| 765 |
+
[len(self.init), len(self.xs), len(self.additional_inputs)],
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
nonlocal grad_spec
|
| 769 |
+
flat_grads, grad_spec = pytree.tree_flatten(
|
| 770 |
+
(
|
| 771 |
+
next_grad_carry,
|
| 772 |
+
[
|
| 773 |
+
prev + cur
|
| 774 |
+
for prev, cur in zip(
|
| 775 |
+
grad_additional_inputs,
|
| 776 |
+
filter_with_masks(
|
| 777 |
+
grad_addi, additional_inputs_tensor_masks
|
| 778 |
+
),
|
| 779 |
+
)
|
| 780 |
+
],
|
| 781 |
+
grad_xs,
|
| 782 |
+
)
|
| 783 |
+
)
|
| 784 |
+
return flat_grads
|
| 785 |
+
|
| 786 |
+
single_step_bw_xs = pytree.tree_map(lambda t: t[0], bw_xs)
|
| 787 |
+
bw_single_step_gm = materialize_as_graph(
|
| 788 |
+
bw_single_step_wrapper,
|
| 789 |
+
tuple(
|
| 790 |
+
pytree.tree_flatten((bw_init, single_step_bw_xs, bw_additional_inputs))[
|
| 791 |
+
0
|
| 792 |
+
]
|
| 793 |
+
),
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
flat_grads = scan_op(
|
| 797 |
+
bw_single_step_gm,
|
| 798 |
+
pytree.tree_flatten(bw_init)[0],
|
| 799 |
+
# TODO: torch.flip copies the tensor, we should optimize it away
|
| 800 |
+
[torch.flip(x, (0,)) for x in pytree.tree_flatten(bw_xs)[0]],
|
| 801 |
+
pytree.tree_flatten(bw_additional_inputs)[0],
|
| 802 |
+
)
|
| 803 |
+
if grad_spec is None:
|
| 804 |
+
raise AssertionError("grad_spec must not be None after scan_op")
|
| 805 |
+
grad_init, grad_additional_inputs, grad_xs = pytree.tree_unflatten(
|
| 806 |
+
flat_grads, grad_spec
|
| 807 |
+
)
|
| 808 |
+
return (
|
| 809 |
+
*grad_init,
|
| 810 |
+
*[torch.flip(elem, (0,)) for elem in grad_xs],
|
| 811 |
+
*fill_none_with_masks(
|
| 812 |
+
grad_additional_inputs, additional_inputs_tensor_masks
|
| 813 |
+
),
|
| 814 |
+
)
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
@scan_op.py_autograd_impl
|
| 818 |
+
def scan_autograd(combine_fn, init, xs, additional_inputs):
|
| 819 |
+
with disable_proxy_modes_tracing():
|
| 820 |
+
hop_partitioned_graph: HopPartitionedGraph = (
|
| 821 |
+
HopGraphMinCutPartitioner.create_partitioned_graph(
|
| 822 |
+
combine_fn,
|
| 823 |
+
(*init, *[x[0] for x in xs], *additional_inputs),
|
| 824 |
+
always_recompute_complex_exprs=True,
|
| 825 |
+
)
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
return ScanAutogradOp.apply(
|
| 829 |
+
hop_partitioned_graph,
|
| 830 |
+
len(init),
|
| 831 |
+
len(xs),
|
| 832 |
+
len(additional_inputs),
|
| 833 |
+
*init,
|
| 834 |
+
*xs,
|
| 835 |
+
*additional_inputs,
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
@scan_op.py_impl(ProxyTorchDispatchMode)
|
| 840 |
+
def scan_proxy_mode(mode, combine_fn, init, xs, additional_inputs):
|
| 841 |
+
return trace_scan(mode, scan_op, combine_fn, init, xs, additional_inputs)
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
@scan_op.py_impl(FakeTensorMode)
|
| 845 |
+
def scan_fake_tensor_mode(mode, combine_fn, init, xs, additional_inputs):
|
| 846 |
+
with mode:
|
| 847 |
+
scan_length = xs[0].shape[0]
|
| 848 |
+
carry, outputs = _extract_carry_and_out(
|
| 849 |
+
combine_fn(
|
| 850 |
+
*init,
|
| 851 |
+
*[first_slice_copy(inp) for inp in xs],
|
| 852 |
+
*additional_inputs,
|
| 853 |
+
),
|
| 854 |
+
len(init),
|
| 855 |
+
)
|
| 856 |
+
out = (
|
| 857 |
+
*carry,
|
| 858 |
+
*(stack_y(t, scan_length) for t in outputs),
|
| 859 |
+
)
|
| 860 |
+
return out
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
@scan_op.py_functionalize_impl
|
| 864 |
+
def scan_functionalize(ctx, combine_fn, init, xs, additional_inputs):
|
| 865 |
+
from torch._higher_order_ops.utils import (
|
| 866 |
+
_check_alias_and_mutation,
|
| 867 |
+
_maybe_run_with_interpreter,
|
| 868 |
+
)
|
| 869 |
+
|
| 870 |
+
unwrapped_xs = ctx.unwrap_tensors(xs)
|
| 871 |
+
unwrapped_init = ctx.unwrap_tensors(init)
|
| 872 |
+
unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs)
|
| 873 |
+
|
| 874 |
+
with ctx.redispatch_to_next():
|
| 875 |
+
functional_combine_fn = ctx.functionalize(
|
| 876 |
+
_maybe_run_with_interpreter(combine_fn)
|
| 877 |
+
)
|
| 878 |
+
sample_unwrapped_xs_sliced = [first_slice_copy(inp) for inp in unwrapped_xs]
|
| 879 |
+
sample_inputs = list(
|
| 880 |
+
itertools.chain(
|
| 881 |
+
unwrapped_init,
|
| 882 |
+
sample_unwrapped_xs_sliced,
|
| 883 |
+
unwrapped_additional_inputs,
|
| 884 |
+
)
|
| 885 |
+
)
|
| 886 |
+
pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
|
| 887 |
+
_check_alias_and_mutation(combine_fn, sample_inputs, "scan", pre_dispatch)
|
| 888 |
+
ret = scan_op(
|
| 889 |
+
functional_combine_fn,
|
| 890 |
+
unwrapped_init,
|
| 891 |
+
unwrapped_xs,
|
| 892 |
+
unwrapped_additional_inputs,
|
| 893 |
+
)
|
| 894 |
+
return ctx.wrap_tensors(ret)
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
@scan_op.py_impl(torch._C._functorch.TransformType.Vmap)
|
| 898 |
+
def scan_batch_rule(interpreter, combine_fn, init, xs, additional_inputs):
|
| 899 |
+
from torch._functorch.vmap import restore_vmap, unwrap_batched, wrap_batched
|
| 900 |
+
|
| 901 |
+
unbatched_args, in_dims = unwrap_batched(
|
| 902 |
+
(init, xs, additional_inputs), interpreter.level()
|
| 903 |
+
)
|
| 904 |
+
# move to last dim to not interfere with scan's batching
|
| 905 |
+
unbatched_init, unbatched_xs, unbatched_additional_inputs = pytree.tree_map(
|
| 906 |
+
lambda x, bdim: x.movedim(bdim, -1) if bdim is not None else x,
|
| 907 |
+
unbatched_args,
|
| 908 |
+
in_dims,
|
| 909 |
+
)
|
| 910 |
+
after_move_dims = tuple(
|
| 911 |
+
pytree.tree_flatten(
|
| 912 |
+
pytree.tree_map(lambda x: -1 if x is not None else None, in_dims)
|
| 913 |
+
)[0]
|
| 914 |
+
)
|
| 915 |
+
|
| 916 |
+
with interpreter.lower():
|
| 917 |
+
out_dims = None
|
| 918 |
+
|
| 919 |
+
def wrapper(*args):
|
| 920 |
+
nonlocal out_dims
|
| 921 |
+
outputs, per_slice_out_dims = restore_vmap(
|
| 922 |
+
combine_fn,
|
| 923 |
+
after_move_dims,
|
| 924 |
+
interpreter.batch_size(),
|
| 925 |
+
interpreter.randomness(),
|
| 926 |
+
)(*args)
|
| 927 |
+
# Note: outputs are not batched, we just move the batch dim to the end
|
| 928 |
+
# this is to avoid it interfering with scan's batching
|
| 929 |
+
outputs = tuple(
|
| 930 |
+
pytree.tree_map(
|
| 931 |
+
lambda out, out_bdim: out.movedim(out_bdim, -1)
|
| 932 |
+
if out_bdim is not None
|
| 933 |
+
else out,
|
| 934 |
+
outputs,
|
| 935 |
+
per_slice_out_dims,
|
| 936 |
+
)
|
| 937 |
+
)
|
| 938 |
+
out_dims = tuple(
|
| 939 |
+
pytree.tree_map(
|
| 940 |
+
lambda out_bdim: -1 if out_bdim is not None else None,
|
| 941 |
+
per_slice_out_dims,
|
| 942 |
+
)
|
| 943 |
+
)
|
| 944 |
+
return outputs
|
| 945 |
+
|
| 946 |
+
unwrapped_out = scan_op(
|
| 947 |
+
wrapper, unbatched_init, unbatched_xs, unbatched_additional_inputs
|
| 948 |
+
)
|
| 949 |
+
|
| 950 |
+
if out_dims is None:
|
| 951 |
+
raise AssertionError("out_dims must not be None after scan_op")
|
| 952 |
+
batched_out = wrap_batched(unwrapped_out, out_dims, interpreter.level())
|
| 953 |
+
return batched_out
|
| 954 |
+
|
| 955 |
+
|
| 956 |
+
# dense implementation for scan. Used for testing only.
|
| 957 |
+
def _fake_scan(combine_fn, init, xs=None, dim=0, reverse=False):
|
| 958 |
+
carry_leaves, carry_spec = pytree.tree_flatten(init)
|
| 959 |
+
inp_leaves, inp_spec = pytree.tree_flatten(xs)
|
| 960 |
+
if xs is None or len(inp_leaves) == 0:
|
| 961 |
+
return init, []
|
| 962 |
+
result_flat = []
|
| 963 |
+
carry = carry_leaves
|
| 964 |
+
op = reversed if reverse else lambda x: x
|
| 965 |
+
|
| 966 |
+
dummy_carry, dummy_out = combine_fn(
|
| 967 |
+
pytree.tree_unflatten(carry, carry_spec),
|
| 968 |
+
pytree.tree_unflatten(
|
| 969 |
+
[first_slice_copy(elem, dim) for elem in inp_leaves],
|
| 970 |
+
inp_spec,
|
| 971 |
+
),
|
| 972 |
+
)
|
| 973 |
+
dummy_out_leaves, dummy_out_spec = pytree.tree_flatten(dummy_out)
|
| 974 |
+
num_leaves = len(dummy_out_leaves)
|
| 975 |
+
|
| 976 |
+
for ind in op(range(inp_leaves[0].size(dim))):
|
| 977 |
+
xs = [elem.select(dim, ind) for elem in inp_leaves]
|
| 978 |
+
|
| 979 |
+
carry, y = combine_fn(
|
| 980 |
+
pytree.tree_unflatten(carry, carry_spec),
|
| 981 |
+
pytree.tree_unflatten(xs, inp_spec),
|
| 982 |
+
)
|
| 983 |
+
carry, _ = pytree.tree_flatten(carry)
|
| 984 |
+
y, _ = pytree.tree_flatten(y)
|
| 985 |
+
result_flat.append(y)
|
| 986 |
+
|
| 987 |
+
results = [
|
| 988 |
+
torch.stack([e[leave_ind] for e in op(result_flat)])
|
| 989 |
+
for leave_ind in range(num_leaves)
|
| 990 |
+
]
|
| 991 |
+
return (
|
| 992 |
+
pytree.tree_unflatten(carry, carry_spec),
|
| 993 |
+
pytree.tree_unflatten(results, dummy_out_spec),
|
| 994 |
+
)
|
venv/lib/python3.14/site-packages/torch/_higher_order_ops/schema.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.utils._pytree as pytree
|
| 7 |
+
from torch._library.fake_class_registry import FakeScriptObject
|
| 8 |
+
from torch._library.opaque_object import is_opaque_type
|
| 9 |
+
from torch.fx.node import Target
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Below is an implementation of generating FunctionSchema from example values.
|
| 13 |
+
# This is helpful for generating FunctionSchema for HigherOrderOperator, where
|
| 14 |
+
# we don't have a function to inspect and each call of the higher order operator
|
| 15 |
+
# would have different schema.
|
| 16 |
+
@dataclass(frozen=True, slots=True)
|
| 17 |
+
class HopArgumentInfo:
|
| 18 |
+
# Could give a name to the operand by default it's empty string.
|
| 19 |
+
name: str
|
| 20 |
+
example_value: Any
|
| 21 |
+
# Provide an default_value
|
| 22 |
+
default_value: Any
|
| 23 |
+
# Whether this argument gets mutated in the hop subgraph.
|
| 24 |
+
# For output, this should always be False
|
| 25 |
+
is_mutated: bool
|
| 26 |
+
kw_only: bool
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class HopArgumentInfoGen:
|
| 30 |
+
@staticmethod
|
| 31 |
+
def from_example(
|
| 32 |
+
example_value: Any,
|
| 33 |
+
*,
|
| 34 |
+
name: str = "",
|
| 35 |
+
default_value: Any | None = None,
|
| 36 |
+
is_mutated: bool = False,
|
| 37 |
+
kw_only: bool = False,
|
| 38 |
+
) -> HopArgumentInfo:
|
| 39 |
+
if default_value is not None:
|
| 40 |
+
if type(example_value) is not type(default_value):
|
| 41 |
+
raise AssertionError(
|
| 42 |
+
f"example_value type {type(example_value)} doesn't match default_value type: {type(default_value)}"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
return HopArgumentInfo(
|
| 46 |
+
name=name,
|
| 47 |
+
example_value=example_value,
|
| 48 |
+
default_value=default_value,
|
| 49 |
+
is_mutated=is_mutated,
|
| 50 |
+
kw_only=kw_only,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class CTypeGen:
|
| 55 |
+
convert_to_base_ty = {
|
| 56 |
+
int: torch._C.IntType.get(),
|
| 57 |
+
float: torch._C.FloatType.get(),
|
| 58 |
+
str: torch._C.StringType.get(),
|
| 59 |
+
bool: torch._C.BoolType.get(),
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
# should return torch._C.JitType but that annotation is busted
|
| 63 |
+
@staticmethod
|
| 64 |
+
def from_example(obj: Any) -> Any:
|
| 65 |
+
import torch
|
| 66 |
+
|
| 67 |
+
if isinstance(obj, torch.fx.GraphModule):
|
| 68 |
+
return torch._C.AnyType.get()
|
| 69 |
+
elif isinstance(obj, torch.SymInt):
|
| 70 |
+
return torch._C.SymIntType.get()
|
| 71 |
+
elif isinstance(obj, torch.SymBool):
|
| 72 |
+
return torch._C.SymBoolType.get()
|
| 73 |
+
elif isinstance(obj, torch.SymFloat):
|
| 74 |
+
return torch._C.FloatType.get()
|
| 75 |
+
elif isinstance(obj, (FakeScriptObject, pytree.TreeSpec)) or is_opaque_type(
|
| 76 |
+
type(obj)
|
| 77 |
+
):
|
| 78 |
+
return torch._C.PyObjectType.get() # pyrefly: ignore[missing-attribute]
|
| 79 |
+
return torch._C._jit_try_infer_type(obj).type()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class CArgumentGen:
|
| 83 |
+
@staticmethod
|
| 84 |
+
def from_hop_argument_info(
|
| 85 |
+
arg_idx: int, arg_info: HopArgumentInfo, is_output: bool = False
|
| 86 |
+
) -> Any:
|
| 87 |
+
typ = CTypeGen.from_example(arg_info.example_value)
|
| 88 |
+
if is_output:
|
| 89 |
+
return torch._C.Argument("", typ, None, None, False, None)
|
| 90 |
+
|
| 91 |
+
alias_set = set({f"alias::a{arg_idx}"}) if arg_info.is_mutated else set()
|
| 92 |
+
alias_info = torch._C._AliasInfo(arg_info.is_mutated, alias_set, alias_set) # type: ignore[attr-defined]
|
| 93 |
+
return torch._C.Argument(
|
| 94 |
+
arg_info.name,
|
| 95 |
+
typ,
|
| 96 |
+
None,
|
| 97 |
+
arg_info.default_value,
|
| 98 |
+
arg_info.kw_only,
|
| 99 |
+
alias_info,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class HopSchemaGenerator:
|
| 104 |
+
def __init__(self, hop: torch._ops.HigherOrderOperator):
|
| 105 |
+
self.arg_infos: list[HopArgumentInfo] = []
|
| 106 |
+
self.example_outputs: list[Any] = []
|
| 107 |
+
self.schema_tree_spec: pytree.TreeSpec | None = None
|
| 108 |
+
self.hop = hop
|
| 109 |
+
|
| 110 |
+
def add_arg(
|
| 111 |
+
self,
|
| 112 |
+
name: str,
|
| 113 |
+
example_value: Any,
|
| 114 |
+
default_value: Any | None = None,
|
| 115 |
+
is_mutated: bool = False,
|
| 116 |
+
kw_only: bool = False,
|
| 117 |
+
) -> None:
|
| 118 |
+
if callable(example_value) and not is_opaque_type(type(example_value)):
|
| 119 |
+
if not isinstance(
|
| 120 |
+
example_value, (torch.fx.GraphModule, torch._ops.OperatorBase)
|
| 121 |
+
):
|
| 122 |
+
raise AssertionError(
|
| 123 |
+
"Expect callable to be a GraphModule or an OperatorBase. Please call materialize_as_graph first "
|
| 124 |
+
f"to turn callable arguments {example_value} into a GraphModule."
|
| 125 |
+
)
|
| 126 |
+
_, flat_spec = pytree.tree_flatten(example_value)
|
| 127 |
+
if not flat_spec.is_leaf():
|
| 128 |
+
raise RuntimeError(
|
| 129 |
+
f"example_value {example_value} is not a leaf node. "
|
| 130 |
+
"Please only add flattened inputs to the hop schema. "
|
| 131 |
+
"If you need some structure in the arguments, please"
|
| 132 |
+
"add_arg for flattened args one by one then "
|
| 133 |
+
"call add_schema_tree_spec to register the original pytree "
|
| 134 |
+
" spec of the args."
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
arg_info = HopArgumentInfoGen.from_example(
|
| 138 |
+
example_value=example_value,
|
| 139 |
+
name=name,
|
| 140 |
+
default_value=default_value,
|
| 141 |
+
is_mutated=is_mutated,
|
| 142 |
+
kw_only=kw_only,
|
| 143 |
+
)
|
| 144 |
+
self.arg_infos.append(arg_info)
|
| 145 |
+
|
| 146 |
+
def add_output(self, output: Any) -> None:
|
| 147 |
+
self.example_outputs.append(output)
|
| 148 |
+
|
| 149 |
+
def add_schema_tree_spec(self, *args: Any, **kwargs: Any) -> None:
|
| 150 |
+
"""schema tree spec is the tree spec from flattening all inputs to the hop with pytree.tree_flatten
|
| 151 |
+
Since torch.FunctionSchema only have proper mutation/alias support for flattened inputs, we need
|
| 152 |
+
to store the tree spec in order to reconstruct the inputs to the hop.
|
| 153 |
+
"""
|
| 154 |
+
self.schema_tree_spec = pytree.tree_flatten((args, kwargs))[1]
|
| 155 |
+
|
| 156 |
+
def gen_schema(self) -> torch._C.FunctionSchema:
|
| 157 |
+
for i, arg_info in enumerate(self.arg_infos):
|
| 158 |
+
arg_spec = pytree.tree_flatten(arg_info.example_value)[1]
|
| 159 |
+
if not arg_spec.is_leaf() and self.schema_tree_spec is None:
|
| 160 |
+
raise RuntimeError(
|
| 161 |
+
f"example_value of arg_infos[{i}] is {arg_info.example_value}, which is not a leaf node. "
|
| 162 |
+
"Please call add_schema_tree_spec to add a schema tree spec first. "
|
| 163 |
+
"Or consider changing the hop's signature to only take flattened arguments."
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
return CFunctionSchemaGen.from_hop_argument_info(
|
| 167 |
+
str(self.hop),
|
| 168 |
+
self.arg_infos,
|
| 169 |
+
HopArgumentInfoGen.from_example(tuple(self.example_outputs), name="out"),
|
| 170 |
+
self.schema_tree_spec,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class CFunctionSchemaGen:
|
| 175 |
+
"""
|
| 176 |
+
Note: [HigherOrderOperator schema generation]
|
| 177 |
+
Each invocation of a HigherOrderOperator will have a different schema.
|
| 178 |
+
For example, the schema of torch.cond varies depending on the true_fn and
|
| 179 |
+
false_fn. So we need a way to generate the schema for each invocation of a HOP.
|
| 180 |
+
|
| 181 |
+
We want to enforce the following invariants for HOP's schema:
|
| 182 |
+
1. Flattened inputs. There should be no pytree structure in it.
|
| 183 |
+
2. Flattened outputs. Note even if the hop returns a single value, it should be wrapped as a tuple.
|
| 184 |
+
3. No aliasing. This includes inp-inp aliasing, inp-out aliasing and out-out aliasing.
|
| 185 |
+
|
| 186 |
+
By enforcing these invariants, we could make HOP's schema meets the requirement of schema parser
|
| 187 |
+
and makes hop easier to handle downstream. For example, suppose we have an invoke_quant_test HOP:
|
| 188 |
+
|
| 189 |
+
class GraphModule(torch.nn.Module):
|
| 190 |
+
def forward(self, l_x_, l_y_):
|
| 191 |
+
subgraph_0 = self.subgraph_0
|
| 192 |
+
invoke_quant_test = torch.ops.higher_order.invoke_quant_test(subgraph_0, l_x_, l_y_, scheme = 'nf4');
|
| 193 |
+
|
| 194 |
+
class subgraph_0(torch.nn.Module):
|
| 195 |
+
def forward(self, l_x_, l_y_):
|
| 196 |
+
add_ = l_x_.add_(1)
|
| 197 |
+
matmul = l_x_ @ l_y_
|
| 198 |
+
sin = matmul.sin()
|
| 199 |
+
child = sin.cos()
|
| 200 |
+
child_1 = l_x_ + l_y_
|
| 201 |
+
child_2 = l_x_ - l_y_
|
| 202 |
+
child_3 = l_x_ @ l_y_
|
| 203 |
+
return (child, child_1, child_2, child_3)
|
| 204 |
+
|
| 205 |
+
By encoding the inputs of hop into a list of HopArgumentInfo and output as a single HopArgumentInfo,
|
| 206 |
+
we would get the following schema:
|
| 207 |
+
invoke_quant_test(Any arg0, Tensor(!) arg1, Tensor arg2, str scheme="\\"nf4\\"") -> (Tensor, Tensor, Tensor, Tensor)
|
| 208 |
+
"""
|
| 209 |
+
|
| 210 |
+
@staticmethod
|
| 211 |
+
def from_hop_argument_info(
|
| 212 |
+
op_name: str,
|
| 213 |
+
inp_argument_info: list[HopArgumentInfo],
|
| 214 |
+
out_argument_info: HopArgumentInfo,
|
| 215 |
+
schema_tree_spec: pytree.TreeSpec | None,
|
| 216 |
+
) -> Any:
|
| 217 |
+
args = []
|
| 218 |
+
for i, arg_info in enumerate(inp_argument_info):
|
| 219 |
+
args.append(CArgumentGen.from_hop_argument_info(i, arg_info))
|
| 220 |
+
|
| 221 |
+
# NOTE: we want the output to always be a single argument with torch._C.TupleType.
|
| 222 |
+
if not isinstance(out_argument_info.example_value, tuple):
|
| 223 |
+
raise AssertionError(
|
| 224 |
+
f"expect out_argument_info's example_value to be a tuple but got {out_argument_info.example_value}"
|
| 225 |
+
)
|
| 226 |
+
if out_argument_info.is_mutated:
|
| 227 |
+
raise AssertionError(
|
| 228 |
+
"out_argument_info.is_mutated should always be set to False."
|
| 229 |
+
)
|
| 230 |
+
rets = None
|
| 231 |
+
if len(out_argument_info.example_value) == 1:
|
| 232 |
+
rets = [CArgumentGen.from_hop_argument_info(0, out_argument_info, True)]
|
| 233 |
+
else:
|
| 234 |
+
rets = [
|
| 235 |
+
CArgumentGen.from_hop_argument_info(
|
| 236 |
+
i,
|
| 237 |
+
HopArgumentInfoGen.from_example(
|
| 238 |
+
name=f"out{i}",
|
| 239 |
+
example_value=val,
|
| 240 |
+
default_value=None,
|
| 241 |
+
is_mutated=False,
|
| 242 |
+
),
|
| 243 |
+
is_output=True,
|
| 244 |
+
)
|
| 245 |
+
for i, val in enumerate(out_argument_info.example_value)
|
| 246 |
+
]
|
| 247 |
+
|
| 248 |
+
return HopSchema(
|
| 249 |
+
op_name,
|
| 250 |
+
"",
|
| 251 |
+
args,
|
| 252 |
+
rets,
|
| 253 |
+
False,
|
| 254 |
+
False,
|
| 255 |
+
schema_tree_spec,
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class HopSchema(torch._C.FunctionSchema):
|
| 260 |
+
def __init__(
|
| 261 |
+
self,
|
| 262 |
+
name: str,
|
| 263 |
+
overload_name: str,
|
| 264 |
+
arguments: list[torch._C.Argument],
|
| 265 |
+
returns: list[torch._C.Argument],
|
| 266 |
+
is_vararg: bool,
|
| 267 |
+
is_varret: bool,
|
| 268 |
+
schema_tree_spec: pytree.TreeSpec | None,
|
| 269 |
+
):
|
| 270 |
+
self.tree_spec = schema_tree_spec
|
| 271 |
+
self.is_vararg = is_vararg
|
| 272 |
+
self.is_varret = is_varret
|
| 273 |
+
super().__init__(
|
| 274 |
+
name,
|
| 275 |
+
overload_name,
|
| 276 |
+
arguments,
|
| 277 |
+
returns,
|
| 278 |
+
self.is_vararg,
|
| 279 |
+
self.is_varret,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
def __deepcopy__(self, memo: Any) -> "HopSchema":
|
| 283 |
+
# Need to additionally copy the tree_spec since
|
| 284 |
+
# it's not a member of torch._C.FunctionSchema
|
| 285 |
+
return HopSchema(
|
| 286 |
+
self.name,
|
| 287 |
+
self.overload_name,
|
| 288 |
+
self.arguments,
|
| 289 |
+
self.returns,
|
| 290 |
+
self.is_vararg,
|
| 291 |
+
self.is_varret,
|
| 292 |
+
copy.deepcopy(self.tree_spec),
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def find_hop_schema(
|
| 297 |
+
gm: torch.fx.GraphModule, target: Target
|
| 298 |
+
) -> list[torch._C.FunctionSchema]:
|
| 299 |
+
schemas = []
|
| 300 |
+
for node in gm.graph.find_nodes(op="call_function", target=target):
|
| 301 |
+
|
| 302 |
+
def _get_example_value(node: torch.fx.Node) -> Any:
|
| 303 |
+
if node.op == "get_attr":
|
| 304 |
+
if not isinstance(node.target, str):
|
| 305 |
+
raise AssertionError(
|
| 306 |
+
f"expected node.target to be str for get_attr, got {type(node.target)}"
|
| 307 |
+
)
|
| 308 |
+
return getattr(gm, node.target)
|
| 309 |
+
else:
|
| 310 |
+
return (
|
| 311 |
+
node.meta["example_value"]
|
| 312 |
+
if "example_value" in node.meta
|
| 313 |
+
else node.meta["val"]
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
fake_args, fake_kwargs = pytree.tree_map_only(
|
| 317 |
+
torch.fx.Node,
|
| 318 |
+
_get_example_value,
|
| 319 |
+
(node.args, node.kwargs),
|
| 320 |
+
)
|
| 321 |
+
schema = node.target.gen_schema(*fake_args, **fake_kwargs)
|
| 322 |
+
schemas.append(schema)
|
| 323 |
+
return schemas
|